Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule a task at go periodically?

Is there any native library or third party support like ScheduledExecutorService by java native library at go lang for production use case?

Please find the code snippet in java 1.8 :

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class TaskScheduler {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Runnable runnable = ()-> {
                // task to run goes here
                System.out.println("Hello !!");
        };
        ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
        service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);

    }

}

It will print Hello !! in every one second.

like image 238
Siddhanta Rath Avatar asked Oct 30 '18 04:10

Siddhanta Rath


People also ask

How do you make a program run periodically?

Go to the Start menu search bar, type in 'task scheduler,' and select the best match. In the Task Scheduler menu, right-click on the Task Scheduler Library, and select New Folder… There, type a name for your folder and click on OK. Now expand the Task Schedule Library.

How does the go scheduler work?

The scheduling mechanism in Go is combine with three main characters, Goroutine, Processor, and Machine. I'll call it GPM model for short in this note. The task unit for scheduling, like a application-level thread. A Goroutine maintains its executing state, but only can be executed while attach to a Processor.


1 Answers

No need to use 3rd party library to achieve that. Simply take the advantage of goroutine and use available time.Sleep() API from time package, then the very same result can be achieved.

Example:

go func() {
    for true {
        fmt.Println("Hello !!")
        time.Sleep(1 * time.Second)
    }
}()

Playground: https://play.golang.org/p/IMV_IAt-VQX


Example using ticker #1

As per suggestion from Siddhanta. Here is one example to achieve the same result by using ticker (taken from go documentation page of ticker, with some modifications following your requirement).

done := make(chan bool)
ticker := time.NewTicker(1 * time.Second)

go func() {
    for {
        select {
        case <-done:
            ticker.Stop()
            return
        case <-ticker.C:
            fmt.Println("Hello !!")
        }
    }
}()

// wait for 10 seconds
time.Sleep(10 *time.Second)
done <- true

The ticker time information (the time when the Hello !! executed) can be taken from ticker.C channel.

case t := <-ticker.C:
    fmt.Println(t)

Playground: https://play.golang.org/p/TN2M-AMr39L


Example using ticker #2

Another simplified example of ticker, taken from https://gobyexample.com/tickers

ticker := time.NewTicker(1 * time.Second)
go func() {
    for range ticker.C {
        fmt.Println("Hello !!")
    }
}()

// wait for 10 seconds
time.Sleep(10 *time.Second)
ticker.Stop()
like image 104
novalagung Avatar answered Oct 22 '22 18:10

novalagung