• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang cron.New函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/robfig/cron.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: main

func main() {

	err := gcfg.ReadFileInto(&cfg, "configAlert.gcfg")
	if err != nil {
		log.Fatalf("Failed to parse gcfg data: %s", err)
	}

	if color != "y" {
		fmt.Println("+=====================================+")
		fmt.Println("|  Checking for page update.........  |")
		fmt.Println("+=====================================+")
		fmt.Println("Use CTRL+C to Exit")
	} else {
		fmt.Println(CLR_G + "+=====================================+" + CLR_N)
		fmt.Println(CLR_G + "|  Checking for page update.........  |" + CLR_N)
		fmt.Println(CLR_G + "+=====================================+" + CLR_N)
		fmt.Println(CLR_R + "Use CTRL+C to Exit" + CLR_N)
	}
	c := cron.New()
	c.AddFunc(cfg.Pushbullet.Cron, func() { getPackPubFree() })
	t := cron.New()
	t.AddFunc(cfg.Pushbullet.Traffic, func() { getTUTrafficPic() })
	go c.Start()
	go t.Start()
	sig := make(chan os.Signal)
	signal.Notify(sig, os.Interrupt, os.Kill)
	<-sig

}
开发者ID:neverlock,项目名称:PacktpubFreeAlert,代码行数:29,代码来源:alert.go


示例2: New

// New creates a new scheduler to manage task scheduling and states
func New(queueUri string, cacheUri string) (Metre, error) {
	if cacheUri == "" {
		cacheUri = LOCALHOST + ":" + CACHEPORT
	} else if strings.Index(cacheUri, ":") == 0 {
		cacheUri = LOCALHOST + ":" + cacheUri
	}

	if queueUri == "" {
		queueUri = LOCALHOST + ":" + QUEUEPORT
	} else if strings.Index(queueUri, ":") == 0 {
		queueUri = LOCALHOST + ":" + queueUri
	}

	cron := *cron.New()
	c, cErr := NewCache(cacheUri)
	if cErr != nil {
		return Metre{}, cErr
	}
	q, qErr := NewQueue(queueUri)
	if qErr != nil {
		return Metre{}, qErr
	}

	s := NewScheduler(q, c)
	m := make(map[string]Task)
	return Metre{cron, q, c, s, m}, nil
}
开发者ID:johnhof,项目名称:metre,代码行数:28,代码来源:metre.go


示例3: New

// New creates a new scheduler to manage task scheduling and states
func New(queueUri string, trackQueueUri string, maxParallel int) (*Metre, error) {
	if queueUri == "" {
		queueUri = LOCALHOST + ":" + QUEUEPORT
	} else if strings.Index(queueUri, ":") == 0 {
		queueUri = LOCALHOST + ":" + queueUri
	}

	if trackQueueUri == "" {
		trackQueueUri = LOCALHOST + ":" + TRACKQUEUEPORT
	} else if strings.Index(trackQueueUri, ":") == 0 {
		trackQueueUri = LOCALHOST + ":" + trackQueueUri
	}

	cron := *cron.New()
	q, qErr := NewQueue(queueUri)
	if qErr != nil {
		return nil, qErr
	}

	t, tErr := NewQueue(trackQueueUri)
	if tErr != nil {
		return nil, tErr
	}

	limitChan := make(chan int, maxParallel)
	m := make(map[string]*Task)
	s := NewScheduler(q, m)
	msgChan := make(chan string)
	return &Metre{cron, q, t, s, m, msgChan, limitChan}, nil
}
开发者ID:gospackler,项目名称:metre,代码行数:31,代码来源:metre.go


示例4: main

func main() {
	manualCorrection, _ := strconv.Atoi(os.Getenv("CORRECTION"))

	c := cron.New()
	c.AddFunc("0 35 13 * * *", func() {
		fmt.Println("Determine timeout")
		duration, err := determineTimeout(200, time.Millisecond*50)
		if err != nil {
			log.Fatal(err)
			return
		}
		startTime := now.MustParse("13:37:00").Add(-(*duration)).Add(time.Millisecond * time.Duration(manualCorrection))
		<-time.After(startTime.Sub(time.Now()))
		gorequest.New().Post(URL).Type("form").Send(requestBody{
			Action: "new",
			Data:   os.Getenv("USERNAME"),
		}).End()
		fmt.Println("Posted!")
	})
	c.Start()
	fmt.Printf("1337 Bot cron started at %s\n", time.Now())

	// Never quit...
	select {}
}
开发者ID:arjandepooter,项目名称:1337bot,代码行数:25,代码来源:main.go


示例5: main

func main() {
	c := cron.New()
	c.AddFunc("5 * * * * *", Hoge)   // 毎分5秒
	c.AddFunc("*/5 * * * * *", Fuga) // 5秒毎

	c.Start()
	isRunning := true

	kami.Get("/", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("OK"))
	})
	kami.Get("/start", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		if !isRunning {
			c.Start()
			isRunning = true
		}
		w.Write([]byte("START OK"))
	})
	kami.Get("/stop", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		if isRunning {
			c.Stop()
			isRunning = false
		}
		w.Write([]byte("STOP OK"))
	})

	defer func() {
		if isRunning {
			c.Stop()
			isRunning = false
		}
	}()

	kami.Serve()
}
开发者ID:kyokomi-sandbox,项目名称:sandbox,代码行数:35,代码来源:main.go


示例6: main

func main() {
	var err error
	db, err = sql.Open("mysql", "root:[email protected](localhost:3306)/zhihu?charset=utf8")
	if err != nil {
		panic(err)
	}
	db.SetMaxOpenConns(200)
	db.SetMaxIdleConns(100)
	defer db.Close()

	f, err := os.OpenFile("debug.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalln("os.Open failed, err:", err)
	}
	defer f.Close()

	w := io.MultiWriter(f, os.Stdout)
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
	log.SetOutput(w)

	log.Println("go working...at", time.Now())

	snapUser()
	//doSavePage()
	log.Println("creating cron task...")
	c := cron.New()
	c.AddFunc("0 12 8,20 * * * ", func() {
		snapUser()
	})
	c.Start()

	rand.Seed(time.Now().UTC().UnixNano())
	port := strconv.Itoa(4000 + rand.Intn(100))
	log.Println(http.ListenAndServe("0.0.0.0:"+port, nil))
}
开发者ID:wanzhihu,项目名称:zhihuSpider,代码行数:35,代码来源:main.go


示例7: startScheduler

func (this *StateEngine) startScheduler() {
	this.Scheduler = cron.New()
	for _, sched := range this.schedules {
		this.Scheduler.AddJob(sched.When, &cronJob{this, sched})
	}
	this.Scheduler.Start()
}
开发者ID:zdebeer99,项目名称:zhome,代码行数:7,代码来源:scheduler.go


示例8: addCronTab

// addCronTab creates a cron server for the given cronTab and
// and begins managing it.
func addCronTab(c cronTab) error {
	// We create a new cron server here since there is no way
	// in the github.com/robfig/cron package to remove entries.
	server := cron.New()

	// Support only traditional cronspec
	// Don't support seconds
	spec := c.Spec.Schedule
	if !strings.HasPrefix(c.Spec.Schedule, "@") {
		spec = "0 " + c.Spec.Schedule

	}
	err := server.AddFunc(spec, func() {
		if err := runCronJob(c); err != nil {
			log.Printf("Error running cron job: %v", err)
		}
	})
	if err != nil {
		return fmt.Errorf("error adding crontab: %v", err)
	}

	cronServers[c.ObjectMeta.UID] = cronServer{
		Server: server,
		Object: c,
	}

	server.Start()

	log.Printf("Added crontab: %s", c.ObjectMeta.Name)

	return nil
}
开发者ID:IanLewis,项目名称:homepage,代码行数:34,代码来源:main.go


示例9: loopStat

func loopStat(ch chan Message, cBroad chan Message, db *mgo.Database) {
	followed := []string{}
	loop := true
	liveBroadcast := make(map[string]time.Time)
	c := cron.New()

	c.AddFunc("0 * * * * *", func() { computeStat(db, followed, 01*time.Minute) })
	c.AddFunc("0 */5 * * * *", func() { computeStat(db, followed, 05*time.Minute) })
	c.AddFunc("0 */15 * * * *", func() { computeStat(db, followed, 15*time.Minute) })
	c.AddFunc("@hourly", func() { computeStat(db, followed, time.Hour) })
	c.AddFunc("0 0 */12 * * *", func() { computeStat(db, followed, 12*time.Hour) })
	c.AddFunc("@daily", func() { computeStat(db, followed, 24*time.Hour) })

	c.Start()
	for loop {
		select {
		case msg := <-ch:
			followed, loop = followedHandler(followed, msg)
		case msg := <-cBroad:
			if msg.s == StartBroadcast {
				addBroadcast(liveBroadcast, msg.v)
			} else if msg.s == EndBroadcast {
				processBroadcast(db, liveBroadcast, msg.v)
			}
		}
	}
}
开发者ID:grsakea,项目名称:kappastat,代码行数:27,代码来源:stat.go


示例10: init

func init() {
	sec := setting.Cfg.Section("database")
	var err error
	x, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%[email protected](%s)/%s?charset=utf8",
		sec.Key("USER").String(),
		sec.Key("PASSWD").String(),
		sec.Key("HOST").String(),
		sec.Key("NAME").String()))
	if err != nil {
		log.FatalD(4, "Fail to init new engine: %v", err)
	}
	x.SetLogger(nil)
	x.SetMapper(core.GonicMapper{})

	if err = x.Sync(new(PkgInfo), new(PkgRef)); err != nil {
		log.FatalD(4, "Fail to sync database: %v", err)
	}

	numOfPackages, _ = x.Count(new(PkgInfo))
	c := cron.New()
	c.AddFunc("@every 5m", func() {
		numOfPackages, _ = x.Count(new(PkgInfo))
	})
	c.Start()
}
开发者ID:hexiaochun,项目名称:gowalker,代码行数:25,代码来源:models.go


示例11: New

// New creates a GoCelery instance with given config
func New(config *Config) (*GoCelery, error) {
	if config.LogLevel == "" {
		config.LogLevel = "info"
	}
	if config.BrokerURL == "" {
		config.BrokerURL = "amqp://localhost"
	}
	gocelery := &GoCelery{
		config: config,
		workerManager: &workerManager{
			brokerURL: config.BrokerURL,
		},
		cron: cron.New(),
	}
	// set up log level
	setupLogLevel(config)

	// try connect to worker
	if err := gocelery.workerManager.Connect(); err != nil {
		return nil, err
	}
	// start cron work
	gocelery.cron.Start()
	return gocelery, nil
}
开发者ID:adfin,项目名称:gocelery,代码行数:26,代码来源:gocelery.go


示例12: startIsmonitor

func startIsmonitor(daemonMode bool) {
	configFile, err := ioutil.ReadFile("config.json")
	if err != nil {
		log.Fatalln(err)
	}

	var config config
	err = json.Unmarshal(configFile, &config)
	if err != nil {
		log.Fatalln(err)
	}

	if daemonMode && config.CronSchedule == nil {
		fmt.Println("Daemon mode but no cron schedule specified. Quitting.")
		os.Exit(1)
	}
	if !daemonMode && config.CronSchedule != nil {
		fmt.Println("Daemon mode not specified but a cron schedule specified. Quitting.")
		os.Exit(1)
	}

	if config.CronSchedule != nil {
		cron := cron.New()
		cron.AddJob(*config.CronSchedule, monitorJob{&config})
		cron.Start()
		defer cron.Stop()
		select {}
	} else {
		runIsmonitor(config)
	}
}
开发者ID:joakim666,项目名称:ismonitor,代码行数:31,代码来源:run_ismonitor.go


示例13: ServeBackGround

// 后台运行的任务
func ServeBackGround() {

	if db.MasterDB == nil {
		return
	}

	// 初始化 七牛云存储
	logic.DefaultUploader.InitQiniu()

	// 常驻内存的数据
	go loadData()

	c := cron.New()

	// 每天对非活跃用户降频
	c.AddFunc("@daily", decrUserActiveWeight)

	// 两分钟刷一次浏览数(TODO:重启丢失问题?信号控制重启?)
	c.AddFunc("@every 2m", logic.Views.Flush)

	if global.OnlineEnv() {
		// 每天生成 sitemap 文件
		c.AddFunc("@daily", logic.GenSitemap)

		// 给用户发邮件,如通知网站最近的动态,每周的晨读汇总等
		c.AddFunc("0 0 4 * * 1", logic.DefaultEmail.EmailNotice)
	}

	c.Start()
}
开发者ID:studygolang,项目名称:studygolang,代码行数:31,代码来源:background.go


示例14: init

func init() {
	var err error
	x, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%[email protected](%s)/%s?charset=utf8",
		setting.Cfg.Section("database").Key("USER").String(),
		setting.Cfg.Section("database").Key("PASSWD").String(),
		setting.Cfg.Section("database").Key("HOST").String(),
		setting.Cfg.Section("database").Key("NAME").String()))
	if err != nil {
		log.Fatal(4, "Fail to init new engine: %v", err)
	}

	x.SetLogger(nil)

	if err = x.Sync(new(Package), new(Revision), new(Downloader),
		new(Block), new(BlockRule)); err != nil {
		log.Fatal(4, "Fail to sync database: %v", err)
	}

	statistic()
	c := cron.New()
	c.AddFunc("@every 5m", statistic)
	c.AddFunc("@every 1h", cleanExpireRevesions)
	c.Start()

	go cleanExpireRevesions()
	if setting.ProdMode {
		go uploadArchives()
		ticker := time.NewTicker(time.Hour)
		go func() {
			for _ = range ticker.C {
				uploadArchives()
			}
		}()
	}
}
开发者ID:harryyeh,项目名称:switch,代码行数:35,代码来源:models.go


示例15: SetCron

func SetCron(count int, cronOnly bool) {
	if !cronOnly {
		ScrapeOrgs()
		ScrapeHb(count)
	}

	c := cron.New()

	c.AddFunc("@every 3h", func() {
		log.Println("start scrapeHb")
		ScrapeHb(count)
		log.Println("end scrapeHb")
	})
	c.AddFunc("@midnight", func() {
		log.Println("start scrapeOrgs")
		ScrapeOrgs()
		log.Println("end scrapeOrgs")
	})
	c.Start()

	for {
		time.Sleep(10000000000000)
		fmt.Println("sleep")
	}
}
开发者ID:seihmd,项目名称:q-o-c,代码行数:25,代码来源:cron.go


示例16: StartScheduler

// StartScheduler will start the scheduler process and handle requests
// in and out.
func StartScheduler(conf *config.Config) {
	c := cron.New()
	c.Start()
	db, err := scheduleDB(conf)
	if err != nil {
		log.Fatalln(err)
	}
	err = db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte(conf.Scheduler.SchedulerDBBucket))
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		log.Fatalln(err)
	}
	/*err = db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("iops"))
		b.ForEach(func(k, v []byte) error {
			c.AddFunc(string(k), func() { "some sort of rally execution code..." })
			return nil
		})
		return nil
	})
	if err != nil {
		log.Fatalln(err)
	}*/
}
开发者ID:briandowns,项目名称:raceway,代码行数:31,代码来源:scheduler.go


示例17: main

func main() {
	// Construct the dsn used for the database
	dsn := os.Getenv("DATABASE_USERNAME") + ":" + os.Getenv("DATABASE_PASSWORD") + "@tcp(" + os.Getenv("DATABASE_HOST") + ":" + os.Getenv("DATABASE_PORT") + ")/" + os.Getenv("DATABASE_NAME")

	// Construct a new AccessorGroup and connects it to the database
	ag := new(accessors.AccessorGroup)
	ag.ConnectToDB("mysql", dsn)

	// Constructs a new ControllerGroup and gives it the AccessorGroup
	cg := new(controllers.ControllerGroup)
	cg.Accessors = ag

	c := cron.New()
	c.AddFunc("0 0 20 * * 1-5", func() { // Run at 2:00pm MST (which is 21:00 UTC) Monday through Friday
		helpers.Webhook(helpers.ReportLeaders(ag))
	})
	c.Start()

	goji.Get("/health", cg.Health)
	goji.Get("/leaderboard", cg.ReportLeaders)
	goji.Post("/slack", cg.Slack) // The main endpoint that Slack hits
	goji.Post("/play", cg.User)
	goji.Post("/portfolio", cg.Portfolio)
	goji.Get("/check/:symbol", cg.Check)
	goji.Post("/buy/:quantity/:symbol", cg.Buy)
	goji.Post("/sell/:quantity/:symbol", cg.Sell)
	goji.Serve()
}
开发者ID:jessemillar,项目名称:stalks,代码行数:28,代码来源:server.go


示例18: RefreshCron

func (ctx *cronContext) RefreshCron(messageSender plugins.MessageSender, channel string) {
	if ctx.cronClient[channel] != nil {
		ctx.cronClient[channel].Stop()
		ctx.cronClient[channel] = nil
	}

	c := cron.New()
	for _, activeCron := range ctx.getTaskMap(channel) {
		if !activeCron.Active {
			continue
		}

		cmd := activeCron.Command
		c.AddFunc(activeCron.Command.CronSpec, func() {
			message := cmd.Message()
			switch cmd.Action {
			case RandomAddAction:
				idx := rd.Intn(len(cmd.Args) - 1)
				log.Println(len(cmd.Args), idx, cmd.Args[idx])
				message = cmd.Args[idx]
			}
			messageSender.SendMessage(message, channel)
		})
	}
	c.Start()

	ctx.cronClient[channel] = c

	if ctx.repository != nil {
		ctx.repository.Save(ctx.cronTaskMap)
	}
}
开发者ID:135yshr,项目名称:slackbot,代码行数:32,代码来源:context.go


示例19: main

func main() {
	flag.Parse()
	err := bakapy.SetupLogging(*LOG_LEVEL)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	config, err := bakapy.ParseConfig(*CONFIG_PATH)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Configuration error: %s\n", err)
		os.Exit(1)
	}

	logger.Debug(string(config.PrettyFmt()))

	scriptPool := bakapy.NewDirectoryScriptPool(config)

	metaman := bakapy.NewMetaManClient(config.MetadataAddr, config.Secret)

	notificators := bakapy.NewNotificatorPool()
	for _, ncConfig := range config.Notificators {
		nc := bakapy.NewScriptedNotificator(scriptPool, ncConfig.Name, ncConfig.Params)
		notificators.Add(nc)
	}

	scheduler := cron.New()
	for jobName, jobConfig := range config.Jobs {
		runSpec := jobConfig.RunAt.SchedulerString()

		if jobConfig.Disabled {
			logger.Warning("job %s disabled, skipping", jobName)
			continue
		}
		storageAddr, exist := config.Storages[jobConfig.Storage]
		if !exist {
			logger.Critical("cannot find storage %s definition in config", jobConfig.Storage)
			os.Exit(1)
		}
		executor := bakapy.NewBashExecutor(jobConfig.Args, jobConfig.Host, jobConfig.Port, jobConfig.Sudo)
		job := bakapy.NewJob(
			jobName, jobConfig, storageAddr,
			scriptPool, executor, metaman,
			notificators,
		)
		logger.Info("adding job %s{%s} to scheduler", jobName, runSpec)
		err := scheduler.AddJob(runSpec, job)
		if err != nil {
			logger.Critical("cannot schedule job %s: %s", jobName, err)
			os.Exit(1)
		}
	}

	if *TEST_CONFIG_ONLY {
		return
	}

	scheduler.Start()
	<-(make(chan int))
}
开发者ID:xuanhan863,项目名称:bakapy,代码行数:60,代码来源:main.go


示例20: main

func main() {
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh,
		syscall.SIGTERM,
		syscall.SIGINT)

	api := anaconda.NewTwitterApi(c.AccessToken, c.AccessTokenSecret)

	c := cron.New()
	c.AddFunc("0 0 7 * * *", func() {
		log.Print("**** START ****")

		f := weather.GetWeatherForecast()
		if needUmbrella(f) {
			m := USER + " 傘持って行ってね♡"
			tweet, _ := api.PostTweet(m, nil)
			log.Print(tweet.Text)
		}

		log.Print("**** END ****")
	})
	c.Start()

	select {
	case s := <-sigCh:
		log.Printf("Recv: %v\n", s)
		os.Exit(0)
	}
}
开发者ID:taka011239,项目名称:teruteru_bot,代码行数:29,代码来源:main.go



注:本文中的github.com/robfig/cron.New函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang cron.Parse函数代码示例发布时间:2022-05-28
下一篇:
Golang config.ReadDefault函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap