diff --git a/internal/tools/cron_task.go b/internal/tools/cron_task.go index 82ce95eda9..84d9193958 100644 --- a/internal/tools/cron_task.go +++ b/internal/tools/cron_task.go @@ -103,6 +103,15 @@ func netlock(rdb redis.UniversalClient, key string, ttl time.Duration) bool { return ok } +// netUnlock release redis lock. +func netUnlock(rdb redis.UniversalClient, key string) error { + _, err := rdb.Del(context.Background(), key).Result() + if err != nil { + return errs.Wrap(err) + } + return nil +} + func cronWrapFunc(config *CronTaskConfig, rdb redis.UniversalClient, key string, fn func()) func() { enableCronLocker := config.CronTask.EnableCronLocker return func() { @@ -114,6 +123,9 @@ func cronWrapFunc(config *CronTaskConfig, rdb redis.UniversalClient, key string, // when acquire redis lock, call fn(). if netlock(rdb, key, 5*time.Second) { + defer func() { + _ = netUnlock(rdb, key) + }() fn() } } diff --git a/internal/tools/cron_task_test.go b/internal/tools/cron_task_test.go index 0bea8a4361..43be7855c3 100644 --- a/internal/tools/cron_task_test.go +++ b/internal/tools/cron_task_test.go @@ -38,6 +38,12 @@ func TestDisLock(t *testing.T) { // set different key assert.Equal(t, true, netlock(rdb, "cron-2", 2*time.Second)) + + // set key and release + assert.Equal(t, true, netlock(rdb, "cron-3", 5*time.Second)) + assert.Equal(t, nil, netUnlock(rdb, "cron-3")) + //retrieve set key + assert.Equal(t, true, netlock(rdb, "cron-3", 5*time.Second)) } //func TestCronWrapFunc(t *testing.T) {