Go Task Scheduler
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.
Features
- 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)
Installation
go get github.com/rakanalh/scheduler
How To Use
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:
Execute a task after 5 seconds.
func MyFunc(arg1 string, arg2 string)
taskID := s.RunAfter(5*time.Second, MyFunc, "Hello", "World")
Execute a task at a specific time.
func MyFunc(arg1 string, arg2 string)
taskID := s.RunAt(time.Now().Add(24 * time.Hour), MyFunc, "Hello", "World")
Execute a task every 1 minute.
func MyFunc(arg1 string, arg2 string)
taskID := s.RunEvery(1 * time.Minute, MyFunc, "Hello", "World")
Examples
The Examples folder contains a bunch of code samples you can look into.
Custom Storage
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
}
TODOs
- [ ] Design a cron-like task schedule for RunEvery method
Credit
This package is heavily inspired by APScheduler for Python & GoCron
License
MIT