Go Task scheduler is a small library that you can use within your application that enables you to execute callbacks (goroutines) after a pre-defined amount of time. GTS also provides task storage which is used to invoke callbacks for tasks which couldn’t be executed during down-time as well as maintaining a history of the callbacks that got executed.
- Execute tasks based after a specific duration or at a specific point in time
- Job stores for history & recovery, provided stores out of the box:
- Sqlite3
- Redis (Coming soon)
go get github.com/rakanalh/scheduler
Instantiate a scheduler as follows:
s := scheduler.New(storage)
GTS currently supports 2 kinds of storages:
- NoOpStorage: Does nothing
noOpStorage := storage.NewNoOpStorage()
- MemoryStorage: Does nothing
memStorage := storage.NewMemoryStorage()
- SqliteStorage: Persists tasks into a SQLite3 database.
sqliteStorage := storage.NewSqlite3Storage()
Example:
storage := storage.NewSqlite3Storage(
storage.Sqlite3Config{
DbName: "db.store",
},
)
if err := storage.Connect(); err != nil {
log.Fatal("Could not connect to db", err)
}
if err := storage.Initialize(); err != nil {
log.Fatal("Could not intialize database", err)
}
and then pass it to the scheduler.
Scheduling tasks can be done in 3 ways:
func MyFunc(arg1 string, arg2 string)
taskID := s.RunAfter(5*time.Second, MyFunc, "Hello", "World")
func MyFunc(arg1 string, arg2 string)
taskID := s.RunAt(time.Now().Add(24 * time.Hour), MyFunc, "Hello", "World")
func MyFunc(arg1 string, arg2 string)
taskID := s.RunEvery(1 * time.Minute, MyFunc, "Hello", "World")
The Examples folder contains a bunch of code samples you can look into.
GTS supports the ability to provide a custom storage, the newly created storage has to implement the TaskStore interface
type TaskStore interface {
Store(task *TaskAttributes) error
Remove(task *TaskAttributes) error
Fetch() ([]TaskAttributes, error)
}
TaskAttributes looks as follows:
type TaskAttributes struct {
Hash string
Name string
LastRun string
NextRun string
Duration string
IsRecurring string
Params string
}
- [ ] Design a cron-like task schedule for RunEvery method
This package is heavily inspired by APScheduler for Python & GoCron
MIT