2018-05-27 07:02:29 -04:00
|
|
|
package task
|
2018-02-08 09:39:46 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2018-05-27 07:02:29 -04:00
|
|
|
// Periodic is a task that runs periodically.
|
|
|
|
type Periodic struct {
|
2018-02-11 17:28:42 -05:00
|
|
|
// Interval of the task being run
|
2018-02-08 09:39:46 -05:00
|
|
|
Interval time.Duration
|
2018-02-11 17:28:42 -05:00
|
|
|
// Execute is the task function
|
|
|
|
Execute func() error
|
2018-02-08 09:39:46 -05:00
|
|
|
|
2018-08-29 17:00:01 -04:00
|
|
|
access sync.Mutex
|
|
|
|
timer *time.Timer
|
|
|
|
running bool
|
2018-05-27 08:42:53 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Periodic) hasClosed() bool {
|
2018-08-29 17:00:01 -04:00
|
|
|
t.access.Lock()
|
|
|
|
defer t.access.Unlock()
|
2018-05-27 08:42:53 -04:00
|
|
|
|
2018-08-29 17:00:01 -04:00
|
|
|
return !t.running
|
2018-05-27 08:42:53 -04:00
|
|
|
}
|
2018-02-08 09:39:46 -05:00
|
|
|
|
2018-05-27 08:42:53 -04:00
|
|
|
func (t *Periodic) checkedExecute() error {
|
|
|
|
if t.hasClosed() {
|
2018-02-08 09:39:46 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := t.Execute(); err != nil {
|
2018-08-29 17:00:01 -04:00
|
|
|
t.access.Lock()
|
|
|
|
t.running = false
|
|
|
|
t.access.Unlock()
|
2018-02-08 09:39:46 -05:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-05-27 08:42:53 -04:00
|
|
|
t.access.Lock()
|
2018-06-29 14:56:10 -04:00
|
|
|
defer t.access.Unlock()
|
|
|
|
|
2018-08-29 17:00:01 -04:00
|
|
|
if !t.running {
|
2018-06-29 14:56:10 -04:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-02-08 09:39:46 -05:00
|
|
|
t.timer = time.AfterFunc(t.Interval, func() {
|
2020-10-11 07:22:46 -04:00
|
|
|
t.checkedExecute()
|
2018-02-08 09:39:46 -05:00
|
|
|
})
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-08-29 17:00:01 -04:00
|
|
|
// Start implements common.Runnable.
|
2018-05-27 07:02:29 -04:00
|
|
|
func (t *Periodic) Start() error {
|
2018-08-29 17:00:01 -04:00
|
|
|
t.access.Lock()
|
|
|
|
if t.running {
|
2018-08-29 17:12:47 -04:00
|
|
|
t.access.Unlock()
|
2018-08-29 17:00:01 -04:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
t.running = true
|
|
|
|
t.access.Unlock()
|
2018-02-08 09:39:46 -05:00
|
|
|
|
|
|
|
if err := t.checkedExecute(); err != nil {
|
2018-08-29 17:00:01 -04:00
|
|
|
t.access.Lock()
|
|
|
|
t.running = false
|
|
|
|
t.access.Unlock()
|
2018-02-08 09:39:46 -05:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-04-03 05:11:54 -04:00
|
|
|
// Close implements common.Closable.
|
2018-05-27 07:02:29 -04:00
|
|
|
func (t *Periodic) Close() error {
|
2018-02-08 09:39:46 -05:00
|
|
|
t.access.Lock()
|
|
|
|
defer t.access.Unlock()
|
|
|
|
|
2018-08-29 17:00:01 -04:00
|
|
|
t.running = false
|
2018-02-08 09:39:46 -05:00
|
|
|
if t.timer != nil {
|
|
|
|
t.timer.Stop()
|
|
|
|
t.timer = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|