Hippocampus's Garden

Under the sea, in the hippocampus's garden...

Ready Steady GO: Call Function Periodically With Timeout

August 16, 2020  |  1 min read  |  44 views

  • このエントリーをはてなブックマークに追加

In this post, I introduce a golang example code that calls some function periodically for a specified amount of time. It was a good exercise for a beginner like me to use goroutines.

The sample code consists of the 3 elements.

  1. Write a function preiodicGreet() that prints a given message periodycally
  2. Set a timeout context in the main function
  3. Call the function preiodicGreet() as a goroutine in the main function
package main

import (
	"context"
	"fmt"
	"time"
)

func periodicGreet(msg string, period time.Duration) {
	t := time.NewTicker(period * time.Second)
	defer t.Stop()
	for {
		select {
		case <-t.C: // Activate periodically
			fmt.Printf(msg)
		}
	}
}

func main() {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second) // Cancel in 5 seconds
	defer cancel()

	go periodicGreet("Hello, World!\n", 1) // Call as a goroutine

	select {
	case <-ctx.Done(): // When time is out
		fmt.Println("Periodic greeting done")
	}
}

References

[1] Goで一定周期で何かを行う方法 - Qiita
[2] contextの使い方 - Qiita


  • このエントリーをはてなブックマークに追加

Written by Shion Honda. If you like this, please share!