Files

124 lines
2.7 KiB
Go
Raw Permalink Normal View History

2025-08-12 06:37:16 -07:00
package backgroundtask_test
import (
"context"
"fmt"
"log/slog"
"sync/atomic"
"time"
"queryorchestration/internal/backgroundtask"
)
func ExampleRunner_basic() {
// Create a simple configuration
type Config struct {
Counter atomic.Int64
}
appConfig := &Config{}
// Create configuration map
config := map[string]any{
"appConfig": appConfig,
}
// Create a work function that increments the counter
workFunc := func(ctx context.Context, logger *slog.Logger, cfg map[string]any) error {
appCfgVal, ok := cfg["appConfig"]
if !ok {
return fmt.Errorf("appConfig not found")
}
c, ok := appCfgVal.(*Config)
if !ok {
return fmt.Errorf("invalid config type")
}
count := c.Counter.Add(1)
logger.Info("work executed", "count", count)
return nil
}
// Initialize the runner with a 100ms interval for quick demonstration
runner, err := backgroundtask.Initialize(
config,
slog.Default(),
workFunc,
backgroundtask.WithInterval(100*time.Millisecond),
)
if err != nil {
panic(err)
}
// Start the runner
if err := runner.Run(); err != nil {
panic(err)
}
// Let it run for a short time
time.Sleep(250 * time.Millisecond)
// Signal immediate work
if err := runner.Signal(); err != nil {
panic(err)
}
// Wait a bit more
time.Sleep(100 * time.Millisecond)
// Shutdown gracefully
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := runner.Shutdown(ctx); err != nil {
panic(err)
}
// Check stats
stats := runner.Stats()
fmt.Printf("Work cycles completed: %d\n", stats.WorkCycles())
fmt.Printf("Counter value: %d\n", appConfig.Counter.Load())
// Can also pretty-print all stats (commented out for example test):
// stats.Print(os.Stdout)
// Output:
// Work cycles completed: 4
// Counter value: 4
}
func ExampleRunner_withTestConfig() {
// Use the provided test configuration
config := backgroundtask.NewTestConfigMap()
testConfig, _ := backgroundtask.GetTestConfig(config)
testConfig.WorkDuration = 50 * time.Millisecond
// Initialize with test work function
runner, err := backgroundtask.Initialize(
config,
slog.Default(),
backgroundtask.TestWorkFunc,
backgroundtask.WithInterval(100*time.Millisecond),
)
if err != nil {
panic(err)
}
// Start the runner
if err := runner.Run(); err != nil {
panic(err)
}
// Wait for some work cycles
if !backgroundtask.WaitForWorkCycles(runner, 2, 300*time.Millisecond) {
panic("expected at least 2 work cycles")
}
// Shutdown
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := runner.Shutdown(ctx); err != nil {
panic(err)
}
fmt.Printf("Test work executed %d times\n", testConfig.Counter.Load())
// Output will show at least 2 executions
}