Create schedule tasks

Hello I’m starting in Go, I come from JAVA, sorry if it’s a very basic question.

I’m creating an application that runs “http” port, now I need to schedule a task that should be run every 1 minute.

I’m worried not to overload the application, so you guys think I should separate one job application (job.exe) and one application http (app.exe)? Or can I keep everything in one application? Would Go bear it?

Thank you very much!

Of course, this should be no problem. Do you have a scheduler/cron library in mind?

Run the separate jobs in separate go routines.

Basic example:

//other code here
go func() {
	ticker := time.NewTicker(60 * time.Second)
	for t := range ticker.C {
		go func() {
			fmt.Println("I'm called every 60 seconds in a separate go routine, the time is:", t)
		}()
	}
}()
//other code here
//call ticker.Stop() to stop the ticker
1 Like

Indeed the easiest is what Chris said, one goroutine per task with a ticker. Careful that tickers leak if you never stop them.

If you want a scheduler with a bounded number of workers, you can have a look at this simple implementation I wrote in a project: https://github.com/dullgiulio/sens3/blob/master/sched.go

Perfect Mrs.

In my case, the task can not stop while the application is running, so just do not I call the stop? Can this slow the application?

I also liked Giulio’s solution (https://github.com/dullgiulio/sens3/blob/master/sched.go), what would be more appropriate in this case?

Thank you so much!

No, if the ticker runs forever, it won’t slow down the application. The problem is only when you exit from the for loop above and you don’t stop the ticker, you are still using memory for the ticker, which cannot be garbage collected.

I would suggest you start with Chris solution, which is extra simple. Only if you run into performance issues (too many tasks, too often), you can do something more fancy as I have shown.

you should take other aspects into count as well like what happens if your jobs fails? what if you wanna retry? what happens in case you want to run a job at some later hour?, I would recommend you look at a job queue that is backed by redis or some sort of storage, with that in place you can have a worker that you run with your app that can process your queue.

Perfect Team,

All the reviews were very well placed, sorry for my lousy English.

What seems simple is not, I need to control the execution of the job, but you provided me with at least 2 clear solutions!

Thank you!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.