猿问

如何定期安排任务?

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


请在 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 !!每隔一秒打印一次。


慕虎7371278
浏览 74回答 1
1回答

汪汪一只猫

无需使用 3rd 方库来实现。只需利用 goroutine 的优势并使用包time.Sleep()中可用的 API time,即可获得相同的结果。例子:go func() {&nbsp; &nbsp; for true {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Hello !!")&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(1 * time.Second)&nbsp; &nbsp; }}()游乐场:https://play.golang.org/p/IMV_IAt-VQX使用代码 #1 的示例根据 Siddhanta 的建议。这是一个使用 ticker 实现相同结果的示例(取自ticker 的 go 文档页面,根据您的要求进行了一些修改)。done := make(chan bool)ticker := time.NewTicker(1 * time.Second)go func() {&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-done:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ticker.Stop()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; case <-ticker.C:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Hello !!")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}()// wait for 10 secondstime.Sleep(10 *time.Second)done <- trueticker时间信息(执行的时间Hello !!)可以从channel中获取ticker.C。case t := <-ticker.C:&nbsp; &nbsp; fmt.Println(t)游乐场:https://play.golang.org/p/TN2M-AMr39L使用代码 #2 的示例另一个简化的 ticker 示例,取自https://gobyexample.com/tickersticker := time.NewTicker(1 * time.Second)go func() {&nbsp; &nbsp; for range ticker.C {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Hello !!")&nbsp; &nbsp; }}()// wait for 10 secondstime.Sleep(10 *time.Second)ticker.Stop()
随时随地看视频慕课网APP

相关分类

Go
我要回答