【问题标题】:How to schedule a task at go periodically?如何定期安排任务?
【发布时间】:2019-04-03 01:51:57
【问题描述】:

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

请在 java 1.8 中找到代码 sn-p :

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 !!

【问题讨论】:

  • I found some implementation in go by using Timer, but not satisfied for the production use-case.我们需要更多解释为什么你不满意
  • 需要一个例程池来为每个例程执行一项任务并且没有内存泄漏:) @xpare
  • 我会说需要一个例程池听起来像是一个 goroutine 会填补的东西。设置计时器并在完成后停止它不会泄漏内存

标签: go scheduled-tasks scheduler


【解决方案1】:

无需使用 3rd 方库即可实现。只需利用 goroutine 并使用 time 包中可用的 time.Sleep() API,即可获得完全相同的结果。

例子:

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

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


使用代码 #1 的示例

根据 Siddhanta 的建议。这是一个使用ticker实现相同结果的示例(取自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

可以从ticker.C频道获取ticker时间信息(Hello !!执行的时间)。

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

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


使用代码 #2 的示例

ticker 的另一个简化示例,取自https://gobyexample.com/tickers

ticker := time.NewTicker(1 * time.Second)
go func() {
    for range ticker.C {
        fmt.Println("Hello !!")
    }
}()

// wait for 10 seconds
time.Sleep(10 *time.Second)
ticker.Stop()

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
相关资源
最近更新 更多