golang:支持每周或者每天固定时间的事件触发器

Posted IGuoSJ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang:支持每周或者每天固定时间的事件触发器相关的知识,希望对你有一定的参考价值。

package main

/*
Author: Guo
Function: 支持每周或者每天固定时间的事件触发器
*/

import (
	"fmt"
	"time"
)

//一天的秒数
const oneDaySecond = 1 * 24 * 60 * 60

//定时器服务
func tickerService(stop chan int) 
	var ticker *time.Ticker
	var duration int64
	var isWeekBak bool
	for 
		now := time.Now()
		// 判断是否是每周六定时,不是的话就是每天固定时间定时
		if isWeekBak && now.Weekday() != time.Sunday 
			//当从每周定时切换到每日定时时,需要清除停止信号,因为可能周定时Ticker并没有创建,也就是说定时任务没有开始
			if len(stop) == 1 
				//fmt.Println("Clean Stop Chan")
				//fmt.Println("Clean Stop Chan Before: ", len(stop))
				<-stop
				//fmt.Println("Clean Stop Chan After: ", len(stop), " Num:", num, " time:", time.Now().Second())
			
			time.Sleep(time.Second * 30)
			fmt.Println("Not This Day.")
			continue
		
		//_, _, second := now.Clock()
		hour, minute, second := now.Clock()
		//当前时间
		//nowTime := time.Date(2020, 7, 18, 22, 25, second, 0, time.Local).Unix()
		nowTime := time.Date(2020, 7, 18, hour, minute, second, 0, time.Local).Unix()
		//每天的定时时间:22:25:30
		//setTime := time.Date(2020, 7, 18, 22, 25, 30, 0, time.Local).Unix()
		setTime := time.Date(2020, 7, 18, 22, 25, 30, 0, time.Local).Unix()
		minusTime := setTime - nowTime
		switch 
		case minusTime == 0:
			duration = oneDaySecond
		case minusTime > 0:
			duration = minusTime
		case minusTime < 0:
			duration = oneDaySecond + minusTime
		
		ticker = time.NewTicker(time.Second * time.Duration(duration))
		select 
		//监听停止定时信号
		case <-stop:
			fmt.Println("Timer Been Shutdown.")
			//停止之前的定时器
			ticker.Stop()
			//模拟定时器切换
			isWeekBak = true
			break
		case <-ticker.C:
			fmt.Printf("Guo Bak Time Is Up. Time: %s\\n", time.Now().Format("2006-01-02 15:04:05"))
			//TODO doSomeThing()
		
	


func main() 
	var stopChan = make(chan int, 1)
	go func() 
		for 
			select 
			case <-time.Tick(time.Second * 10):
				//清除之前的停止信号,因为可能不存在消费者,导致阻塞
				if len(stopChan) != 0 
					<-stopChan
					//fmt.Println("Output: ", len(stopChan), " time:", time.Now().Second())
				
				//发出停止信号,模拟定时的“改变事件”
				stopChan <- 100
				//fmt.Println("Input: ", len(stopChan), " time:", time.Now().Second())
				fmt.Printf("Guo Stop Time Is Up. Time: %s\\n", time.Now().Format("2006-01-02 15:04:05"))
			
		
	()
	go tickerService(stopChan)
	for
		time.Sleep(time.Second * 1000)
	


以上是关于golang:支持每周或者每天固定时间的事件触发器的主要内容,如果未能解决你的问题,请参考以下文章

四博智慧物联系统快速入门-5.定时任务

nginx HttpLimitReqModule 是不是支持每小时/每天/每周?

Golang实验性功能SetMaxHeap 固定值GC

每周在特定日期和时间触发通知

spring定时任务时间表达式如何写? 每周星期三晚上8点执行

当在 jquery 中触发文本字段 onfocus 事件时,标题不固定