代码拉取完成,页面将自动刷新
package gcron
import (
"fmt"
"time"
)
// ForegroundExecuteWithInterval 执行函数,并每隔 duration 执行一次,阻塞进程执行
func ForegroundExecuteWithInterval(execution func(), duration time.Duration) {
t := time.NewTicker(duration) // 定时器
//defer t.Stop() // 主协程退出时停止定时器,暂时注释掉了,有问题
execution() // 立即执行,第一次立即执行一次,然后每隔duration 执行一次
for {
select {
case <-t.C:
execution()
}
}
}
// BackgroundExecuteWithInterval 启动后台执行函数,每隔 duration 执行一次,并在后台独立运行,不阻塞主进程
func BackgroundExecuteWithInterval(execution func(), duration time.Duration, done <-chan struct{}) {
// 以下是 done <-chan struct{} 的具体用法说明:
//主协程通过 close(done) 通知退出。
//其他协程通过 select 语句监听 done 通道,当通道被关闭时自动触发退出逻辑。
ticker := time.NewTicker(duration) // 定时器
//defer ticker.Stop() // 在函数退出时停止定时器
// 立即执行一次
execution()
// 启动后台协程,进行定时执行
go func() {
for {
select {
case <-ticker.C:
// 定时器触发,执行指定函数
execution()
case <-done:
// 如果 done 通道关闭,则退出协程
return
}
}
}()
}
func main() {
// 前台执行
ForegroundExecuteWithInterval(func() { fmt.Println("hello world") }, 5*time.Second)
// 后台执行
// 创建 done 通道,用于控制后台协程停止
done := make(chan struct{})
// 定义一个执行函数
execution := func() {
// 定期执行的操作
fmt.Println("执行函数执行了")
}
// 启动后台任务,每2秒执行一次
BackgroundExecuteWithInterval(execution, 2*time.Second, done)
// 主线程
fmt.Println("main thread")
// 模拟主程序运行 10 秒后关闭后台任务
time.Sleep(10 * time.Second)
close(done)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。