how do i change this so it runs every 30 seconds and gracefully stops from keyboard…
- User
how do i change this so it runs every 30 seconds and gracefully stops from keyboard interrupt and docker
func main() { plans := retrievePlans()
for i := range plans { htmlparser.ParseHTML(plans[i].URL) }}
- Assistant
To modify your program so that it runs every 30 seconds, handles keyboard interrupts gracefully, and responds to Docker stop commands, you need to:
- Use a time.Ticker for scheduling.
- Capture SIGINT (Ctrl+C) for graceful shutdown via keyboard interrupts.
- Capture SIGTERM to handle Docker stop commands (which sends SIGTERM).
Here is a sample implementation in Go:
package main import ( "fmt" "os" "os/signal" "sync" "syscall" "time" ) func retrievePlans() []string { // Mock function to mimic retrieving plan URLs return []string{ "http://example.com/plan1", "http://example.com/plan2", } } func parseHTML(url string) { // Mock function to mimic HTML parsing fmt.Println("Parsing", url) } func main() { plans := retrievePlans() ticker := time.NewTicker(30 * time.Second) done := make(chan bool) signals := make(chan os.Signal, 1) // Handle SIGINT and SIGTERM for graceful shutdown signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM) var wg sync.WaitGroup go func() { for { select { case <-ticker.C: for i := range plans { wg.Add(1) go func(url string) { defer wg.Done() parseHTML(url) }(plans[i]) } wg.Wait() // Wait for all goroutines to complete before the next tick case <-signals: fmt.Println("Shutdown signal received") ticker.Stop() // Stop the ticker done <- true // Signal the main routine to stop return case <-done: return } } }() <-done // Wait for the signal to terminate fmt.Println("Shutting down gracefully...") }Explanation:
-
Ticker: The
time.Tickeris used to run a block of code every 30 seconds. -
Goroutines and WaitGroups: This example makes use of goroutines to parse HTML concurrently for each plan.
sync.WaitGroupensures that all goroutines complete their work before the next tick occurs. -
Signal Handling: By listening to
SIGINT(Ctrl+C) andSIGTERM(Docker stop and Kubernetes pod termination), the process can be interrupted gracefully. Handling these signals allows the application to clean up resources or finish processing before shutting down. -
Graceful Shutdown: Upon receiving a termination signal, the process stops the ticker and signals the main loop (using
donechannel) to finish execution. This approach ensures that all tasks are completed before the application exits.
This code is designed to minimize the risk of data corruption and ensure that all parsing tasks are properly completed before the application terminates. Adjust the
retrievePlansandparseHTMLfunctions according to your actual implementation details.