如何定期安排任务?

Sid*_*ath 4 scheduler scheduled-tasks go

有没有任何本地库或第三方支持,例如ScheduledExecutorServicego lang用于生产用例的java本机库?

请在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);

    }

}
Run Code Online (Sandbox Code Playgroud)

它将Hello !!每秒打印一次.

我通过使用发现了一些实现ScheduledExecutorService,但对生产用例不满意.

nov*_*ung 7

无需使用第三方库来实现这一目标.只需利用goroutine的优势并使用包中的可用time.Sleep()API time,就可以实现完全相同的结果.

例:

go func() {
    for true {
        fmt.Println("Hello !!")
        time.Sleep(1 * time.Second)
    }
}()
Run Code Online (Sandbox Code Playgroud)

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


使用自动收报机#1的示例

根据Siddhanta的建议.以下是使用自动收报机获取相同结果的一个示例(取自自动收录器的go文档页面,并根据您的要求进行一些修改).

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
Run Code Online (Sandbox Code Playgroud)

Hello !!可以从ticker.C频道获取自动收报机时间信息(执行时间).

case t := <-ticker.C:
    fmt.Println(t)
Run Code Online (Sandbox Code Playgroud)

游乐场: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()
Run Code Online (Sandbox Code Playgroud)

  • 实际上最好使用[time.Ticker](https://golang.org/pkg/time/#NewTicker) (4认同)