5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Go】プログラム内で定期実行させるライブラリ Cron

Last updated at Posted at 2021-05-20

docker コンテナ内でcrontabがうまく動作しなかったので、Goプログラム内で定期実行をさせた。

実行環境

  • golang 1.16.4-buster コンテナ

インストール

go get github.com/robfig/cron/v3@v3.0.0

Cron

まず、コード例

main.go
package main

import (
        "fmt"
        "github.com/robfig/cron/v3"
)

func main() {
	c := cron.New()

	// 3秒ごと、「Hello World!!」と出力される
	c.AddFunc("@every 3s", printHelloWorld)

	// 毎日、午前8時に「Hello World!!」と出力される
	// cron式でもスケジューリングの設定ができる
	c.AddFunc("0 8 * * *", printHelloWorld)
	
	//追加したジョブを開始
	c.Start()

	// プログラムを即終了させない
	runtime.Goexit()
}

func printHelloWorld() {
	fmt.Println("Hello World!!")
}

参考記事

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?