dousi7579 2018-10-30 04:04
浏览 105
已采纳

如何定期安排任务?

Is there any native library or third party support like ScheduledExecutorService by java native library at go lang for production use case?

Please find the code snippet in 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);

    }

}

It will print Hello !! in every one second.

  • 写回答

1条回答 默认 最新

  • dsz90288 2018-10-30 04:16
    关注

    No need to use 3rd party library to achieve that. Simply take the advantage of goroutine and use available time.Sleep() API from time package, then the very same result can be achieved.

    Example:

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

    Playground: https://play.golang.org/p/IMV_IAt-VQX


    Example using ticker #1

    As per suggestion from Siddhanta. Here is one example to achieve the same result by using ticker (taken from go documentation page of ticker, with some modifications following your requirement).

    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
    

    The ticker time information (the time when the Hello !! executed) can be taken from ticker.C channel.

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

    Playground: https://play.golang.org/p/TN2M-AMr39L


    Example using ticker #2

    Another simplified example of ticker, taken from 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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮