Initial commit

This commit is contained in:
yan.y
2024-03-27 23:25:08 +08:00
commit 0884384e91
127 changed files with 9353 additions and 0 deletions
+34
View File
@@ -0,0 +1,34 @@
package cron_server
import (
"fmt"
"sync"
"time"
)
var (
once sync.Once
cc *cron.Cron
)
// CronInstance cron single instance
func CronInstance() *cron.Cron {
once.Do(func() {
cc = cron.New(cron.WithSeconds())
})
return cc
}
// DoOnce run job once time,this job will run after 2 second
func DoOnce(job cron.Job, t ...time.Duration) error {
once := time.Now().Add(2 * time.Second)
if len(t) == 1 {
once = time.Now().Add(t[0] * time.Second)
}
onceSpec := fmt.Sprintf("%d %d %d %d %d %d", once.Second(), once.Minute(), once.Hour(), once.Day(), once.Month(), once.Weekday())
_, err := CronInstance().AddJob(onceSpec, job)
if err != nil {
return err
}
return nil
}
+16
View File
@@ -0,0 +1,16 @@
package cron_server
import "testing"
func TestCronInstance(t *testing.T) {
t.Run("Test cron instance init", func(t *testing.T) {
instance := CronInstance()
if instance == nil {
t.Error("Cron Instance init fail.")
}
instance1 := CronInstance()
if instance != instance1 {
t.Error("Cron Instance is change.")
}
})
}