golang 定时器

chen yuwen · · 6646 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

代码文件timer.go:

package main

import (
	"bytes"
	"fmt"
	"github.com/unknwon/goconfig"
	"os/exec"
	"time"
)

var config *goconfig.ConfigFile

func init() {
	path := "./config.ini"
	conf, err := goconfig.LoadConfigFile(path)
	if err != nil {
		fmt.Println(err)
	}
	config = conf
}
 
func main() {
	t := time.NewTicker(1 * time.Second)
	for {
		select {
		case <-t.C:
			run()
		}
	}
}

func run() {
	startTimestamp, _ := config.Int64("time", "startTimestamp")
	loopSeconds, _ := config.Int64("time", "loopSeconds")
	unix := time.Now().Unix()
	if startTimestamp <= unix && (unix-startTimestamp)%loopSeconds == 0 {
		cmd()
	}
}

func cmd() {
	scriptBinPath, _ := config.GetValue("cmd", "scriptBinPath")
	filepath, _ := config.GetValue("cmd", "filePath")
	params, _ := config.GetValue("cmd", "params")
	cmd := exec.Command(scriptBinPath, filepath, params)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Start()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Waiting for command to finish...")
	err = cmd.Wait()
	if err != nil {
		fmt.Printf("Command finished with error: %v", err)
	}
	fmt.Println(out.String())
}

配置文件config.ini放在代码生成可执行文件同级目录

[time]
;开始的时间戳
startTimestamp:1396361928
;循环的时间间隔
loopSeconds:3
[cmd]
;执行的脚本
scriptBinPath:E:/zendloader+redis+iis/php-5.3.28-nts-Win32-VC9-x86/php.exe
;被执行的文件
filePath:D:/jianguo/command/application/command/demo.php
;参数
params:



有疑问加站长微信联系(非本文作者)

本文来自:开源中国博客

感谢作者:chen yuwen

查看原文:golang 定时器

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

6646 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传