如何定期安排任务?

时间:2018-10-30 04:04:21

标签: go scheduled-tasks scheduler

在go lang上是否有Java原生库提供的原生库或第三方支持(如ScheduledExecutorService)用于生产用例?

请在Java 1.8中找到代码片段:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class TaskScheduler {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Runnable runnable = ()-> {
                // task to run goes here
                System.out.println("Hello !!");
        };
        ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
        service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);

    }

}

它将每秒钟打印Hello !!

我通过使用Timer找到了一些实现,但对生产用例不满意。

1 个答案:

答案 0 :(得分:5)

无需使用第三方库即可实现。只需利用goroutine的优势并使用time.Sleep()软件包中可用的time API,即可实现完全相同的结果。

示例:

go func() {
    for true {
        fmt.Println("Hello !!")
        time.Sleep(1 * time.Second)
    }
}()

游乐场:https://play.golang.org/p/IMV_IAt-VQX


使用代码1的示例

根据Siddhanta的建议。这是一个使用代码来实现相同结果的示例(摘自go documentation page of ticker,并根据需要进行了一些修改)。

done := make(chan bool)
ticker := time.NewTicker(1 * time.Second)

go func() {
    for {
        select {
        case <-done:
            ticker.Stop()
            return
        case <-ticker.C:
            fmt.Println("Hello !!")
        }
    }
}()

// wait for 10 seconds
time.Sleep(10 *time.Second)
done <- true

可以从Hello !!通道获取行情自动收录器时间信息(执行ticker.C的时间)。

case t := <-ticker.C:
    fmt.Println(t)

游乐场:https://play.golang.org/p/TN2M-AMr39L


使用代码2的示例

股票代码的另一个简化示例,取自https://gobyexample.com/tickers

ticker := time.NewTicker(1 * time.Second)
go func() {
    for t := range ticker.C {
        _ = t // we don't print the ticker time, so assign this `t` variable to underscore `_` to avoid error
        fmt.Println("Hello !!")
    }
}()

// wait for 10 seconds
time.Sleep(10 *time.Second)
ticker.Stop()
相关问题