Testing Long-Running Workflows: Timers, Sleeps, and Deadlines

Testing Long-Running Workflows: Timers, Sleeps, and Deadlines

One of Temporal's most powerful features is also one of its most challenging to test: the ability to write workflows that sleep for hours, days, or even years. A workflow.Sleep(24 * time.Hour) in your code would make tests impossibly slow if executed in real time. Temporal solves this with its TestWorkflowEnvironment's time skipping capabilities, but using them correctly requires understanding how the simulated clock works and how to structure tests around it.

How Temporal's Simulated Clock Works

When you run a workflow in TestWorkflowEnvironment, time doesn't advance automatically in real-time. Instead:

  1. The test clock starts at the current wall time when the environment is created
  2. Time advances automatically when all workflow coroutines are blocked on timers (no other work to do)
  3. You can explicitly skip time using env.Sleep() or register callbacks at future time points

This means a workflow that does workflow.Sleep(24 * time.Hour) will complete almost instantly in tests—the environment detects that all goroutines are blocked waiting for the timer and advances the clock to unblock them.

Here's the key insight: the test environment never blocks waiting for real time. It always advances the simulated clock to the next scheduled event.

Basic Timer Testing

package workflow_test

import (
    "testing"
    "time"

    "github.com/stretchr/testify/mock"
    "github.com/stretchr/testify/suite"
    "go.temporal.io/sdk/testsuite"
    "go.temporal.io/sdk/workflow"
)

// A simple workflow that waits 24 hours then sends a reminder
func DailyReminderWorkflow(ctx workflow.Context, userID string) error {
    ao := workflow.ActivityOptions{
        StartToCloseTimeout: 30 * time.Second,
    }
    ctx = workflow.WithActivityOptions(ctx, ao)

    // Send initial confirmation
    err := workflow.ExecuteActivity(ctx, SendConfirmationActivity, userID).Get(ctx, nil)
    if err != nil {
        return err
    }

    // Wait 24 hours
    workflow.Sleep(ctx, 24*time.Hour)

    // Send reminder
    return workflow.ExecuteActivity(ctx, SendReminderActivity, userID).Get(ctx, nil)
}

type TimerTestSuite struct {
    suite.Suite
    testsuite.WorkflowTestSuite
    env *testsuite.TestWorkflowEnvironment
}

func (s *TimerTestSuite) SetupTest() {
    s.env = s.NewTestWorkflowEnvironment()
}

func (s *TimerTestSuite) AfterTest(suiteName, testName string) {
    s.env.AssertExpectations(s.T())
}

func TestTimerTestSuite(t *testing.T) {
    suite.Run(t, new(TimerTestSuite))
}

func (s *TimerTestSuite) TestDailyReminderWorkflow() {
    s.env.RegisterWorkflow(DailyReminderWorkflow)
    s.env.RegisterActivity(SendConfirmationActivity)
    s.env.RegisterActivity(SendReminderActivity)

    var activityCallOrder []string

    s.env.OnActivity(SendConfirmationActivity, mock.Anything, "user-123").
        Return(func(ctx context.Context, userID string) error {
            activityCallOrder = append(activityCallOrder, "confirmation")
            return nil
        })
    s.env.OnActivity(SendReminderActivity, mock.Anything, "user-123").
        Return(func(ctx context.Context, userID string) error {
            activityCallOrder = append(activityCallOrder, "reminder")
            return nil
        })

    // This executes in milliseconds despite the 24-hour sleep
    s.env.ExecuteWorkflow(DailyReminderWorkflow, "user-123")

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())
    s.Equal([]string{"confirmation", "reminder"}, activityCallOrder)
}

The test completes in milliseconds even though the workflow sleeps for 24 hours. The test environment automatically skips the simulated clock forward when all goroutines are waiting.

Verifying Time Has Elapsed

Sometimes you need to verify that the workflow correctly waited the expected amount of time before proceeding. Use RegisterDelayedCallback to inspect state at specific times:

func (s *TimerTestSuite) TestReminderSentAfterCorrectDelay() {
    s.env.RegisterWorkflow(DailyReminderWorkflow)
    s.env.RegisterActivity(SendConfirmationActivity)
    s.env.RegisterActivity(SendReminderActivity)

    s.env.OnActivity(SendConfirmationActivity, mock.Anything, mock.Anything).Return(nil)
    s.env.OnActivity(SendReminderActivity, mock.Anything, mock.Anything).Return(nil)

    confirmationSentAt := time.Time{}
    reminderSentAt := time.Time{}

    s.env.OnActivity(SendConfirmationActivity, mock.Anything, "user-456").
        Return(func(ctx context.Context, userID string) error {
            confirmationSentAt = s.env.Now()
            return nil
        })

    s.env.OnActivity(SendReminderActivity, mock.Anything, "user-456").
        Return(func(ctx context.Context, userID string) error {
            reminderSentAt = s.env.Now()
            return nil
        })

    s.env.ExecuteWorkflow(DailyReminderWorkflow, "user-456")

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())

    // Verify the reminder was sent approximately 24 hours after confirmation
    elapsed := reminderSentAt.Sub(confirmationSentAt)
    s.InDelta(24*time.Hour.Seconds(), elapsed.Seconds(), 1.0)
}

Cron Workflows

Temporal supports cron-style scheduling natively. Testing cron workflows requires advancing the clock through multiple cron intervals:

// A workflow that runs every day at midnight and sends a report
func DailyReportWorkflow(ctx workflow.Context, reportConfig ReportConfig) error {
    ao := workflow.ActivityOptions{
        StartToCloseTimeout: 5 * time.Minute,
    }
    ctx = workflow.WithActivityOptions(ctx, ao)

    var reportData ReportData
    err := workflow.ExecuteActivity(ctx, GenerateReportActivity, reportConfig).Get(ctx, &reportData)
    if err != nil {
        return err
    }

    return workflow.ExecuteActivity(ctx, EmailReportActivity, reportConfig.Recipients, reportData).Get(ctx, nil)
}

// Starting a cron workflow
func StartDailyReportCron(client client.Client, config ReportConfig) (client.WorkflowRun, error) {
    return client.ExecuteWorkflow(
        context.Background(),
        client.StartWorkflowOptions{
            ID:           "daily-report",
            TaskQueue:    "reports",
            CronSchedule: "0 0 * * *", // Every day at midnight
        },
        DailyReportWorkflow,
        config,
    )
}

Testing that a cron workflow runs the correct number of times:

func (s *TimerTestSuite) TestCronWorkflowRunsCorrectly() {
    s.env.RegisterWorkflow(DailyReportWorkflow)
    s.env.RegisterActivity(GenerateReportActivity)
    s.env.RegisterActivity(EmailReportActivity)

    runCount := 0

    s.env.OnActivity(GenerateReportActivity, mock.Anything, mock.Anything).
        Return(func(ctx context.Context, config ReportConfig) (ReportData, error) {
            runCount++
            return ReportData{RecordCount: 100, GeneratedAt: time.Now()}, nil
        })
    s.env.OnActivity(EmailReportActivity, mock.Anything, mock.Anything, mock.Anything).
        Return(nil)

    // Set cron schedule
    s.env.SetTestTimeout(8 * 24 * time.Hour) // Set max test duration

    config := ReportConfig{
        Recipients: []string{"admin@example.com"},
        Type:       "summary",
    }

    s.env.ExecuteWorkflow(DailyReportWorkflow, config)

    // The test environment will run the workflow once per cron interval
    // until the test timeout is reached
    s.True(s.env.IsWorkflowCompleted())
}

For more control over cron testing, you can test individual runs with explicit time control:

func (s *TimerTestSuite) TestCronWorkflowSkipsOnWeekends() {
    s.env.RegisterWorkflow(WeekdayReportWorkflow)
    s.env.RegisterActivity(GenerateWeekdayReportActivity)

    var runDays []time.Weekday

    s.env.OnActivity(GenerateWeekdayReportActivity, mock.Anything, mock.Anything).
        Return(func(ctx context.Context, config ReportConfig) (ReportData, error) {
            runDays = append(runDays, s.env.Now().Weekday())
            return ReportData{}, nil
        })

    // Set start time to Monday
    startTime := getNextMonday()
    s.env.SetStartTime(startTime)

    // Register callback to stop after one week
    s.env.RegisterDelayedCallback(func() {
        // Nothing - just let it run
    }, 7*24*time.Hour)

    config := ReportConfig{Recipients: []string{"team@example.com"}}
    s.env.ExecuteWorkflow(WeekdayReportWorkflow, config)

    // Should only run on weekdays
    for _, day := range runDays {
        s.NotEqual(time.Saturday, day)
        s.NotEqual(time.Sunday, day)
    }
}

Testing Timer-Based Retries

A common pattern is using timers to implement custom retry logic with specific backoff:

func RetryWithBackoffWorkflow(ctx workflow.Context, taskID string) error {
    maxAttempts := 5
    baseDelay := 1 * time.Minute

    for attempt := 1; attempt <= maxAttempts; attempt++ {
        ao := workflow.ActivityOptions{
            StartToCloseTimeout: 30 * time.Second,
            // No automatic retries — we handle them manually
            RetryPolicy: &temporal.RetryPolicy{MaximumAttempts: 1},
        }
        ctx = workflow.WithActivityOptions(ctx, ao)

        err := workflow.ExecuteActivity(ctx, ProcessTaskActivity, taskID).Get(ctx, nil)
        if err == nil {
            return nil // Success
        }

        if attempt == maxAttempts {
            return fmt.Errorf("task %s failed after %d attempts: %w", taskID, maxAttempts, err)
        }

        // Exponential backoff
        delay := time.Duration(attempt) * baseDelay
        workflow.GetLogger(ctx).Info("Attempt failed, waiting before retry",
            "attempt", attempt,
            "delay", delay,
        )
        workflow.Sleep(ctx, delay)
    }

    return nil
}

func (s *TimerTestSuite) TestRetryWithBackoffWorkflow() {
    s.env.RegisterWorkflow(RetryWithBackoffWorkflow)
    s.env.RegisterActivity(ProcessTaskActivity)

    var attemptTimes []time.Time

    // Fail first 3 attempts, succeed on 4th
    callCount := 0
    s.env.OnActivity(ProcessTaskActivity, mock.Anything, "task-backoff").
        Return(func(ctx context.Context, taskID string) error {
            attemptTimes = append(attemptTimes, s.env.Now())
            callCount++
            if callCount < 4 {
                return errors.New("transient failure")
            }
            return nil
        })

    s.env.ExecuteWorkflow(RetryWithBackoffWorkflow, "task-backoff")

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())
    s.Equal(4, callCount)

    // Verify backoff intervals
    // Attempt 1 at t=0
    // Attempt 2 at t=1min (after 1min delay)
    // Attempt 3 at t=3min (after 2min delay)
    // Attempt 4 at t=6min (after 3min delay)
    s.Len(attemptTimes, 4)

    delay1 := attemptTimes[1].Sub(attemptTimes[0])
    delay2 := attemptTimes[2].Sub(attemptTimes[1])
    delay3 := attemptTimes[3].Sub(attemptTimes[2])

    s.InDelta(time.Minute.Seconds(), delay1.Seconds(), 1.0)
    s.InDelta((2 * time.Minute).Seconds(), delay2.Seconds(), 1.0)
    s.InDelta((3 * time.Minute).Seconds(), delay3.Seconds(), 1.0)
}

Testing Workflow Deadlines

Workflows can have execution timeouts. Testing that a workflow correctly handles approaching its deadline:

func TimeSensitiveWorkflow(ctx workflow.Context, jobID string) error {
    ao := workflow.ActivityOptions{
        StartToCloseTimeout: 1 * time.Hour,
    }
    ctx = workflow.WithActivityOptions(ctx, ao)

    // Check if we're close to the workflow deadline
    info := workflow.GetInfo(ctx)
    deadline := info.WorkflowExecutionTimeout

    if deadline > 0 && deadline < 30*time.Minute {
        // Not enough time to do the full job
        return workflow.ExecuteActivity(ctx, AbortJobActivity, jobID).Get(ctx, nil)
    }

    // Full processing
    err := workflow.ExecuteActivity(ctx, ProcessJobActivity, jobID).Get(ctx, nil)
    if err != nil {
        return err
    }

    // Simulate long work that might approach deadline
    workflow.Sleep(ctx, 45*time.Minute)

    return workflow.ExecuteActivity(ctx, FinalizeJobActivity, jobID).Get(ctx, nil)
}

func (s *TimerTestSuite) TestWorkflowDeadlineHandling() {
    s.env.RegisterWorkflow(TimeSensitiveWorkflow)
    s.env.RegisterActivity(ProcessJobActivity)
    s.env.RegisterActivity(FinalizeJobActivity)
    s.env.RegisterActivity(AbortJobActivity)

    // Test with sufficient deadline
    s.env.OnActivity(ProcessJobActivity, mock.Anything, "job-1").Return(nil)
    s.env.OnActivity(FinalizeJobActivity, mock.Anything, "job-1").Return(nil)

    s.env.ExecuteWorkflow(TimeSensitiveWorkflow, "job-1")
    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())
}

func (s *TimerTestSuite) TestWorkflowDeadlineEnforced() {
    s.env.RegisterWorkflow(TimeSensitiveWorkflow)
    s.env.RegisterActivity(ProcessJobActivity)
    s.env.RegisterActivity(FinalizeJobActivity)

    // Mock the process activity to succeed but finalize never gets called
    // because the workflow times out
    s.env.OnActivity(ProcessJobActivity, mock.Anything, "job-2").Return(nil)

    // Set a very short workflow execution timeout
    s.env.SetTestTimeout(20 * time.Minute)

    s.env.ExecuteWorkflow(TimeSensitiveWorkflow, "job-2")

    s.True(s.env.IsWorkflowCompleted())
    err := s.env.GetWorkflowError()
    s.Error(err)
    s.Contains(err.Error(), "timeout")
}

The SkipTime and FastForward Patterns

When you need more explicit control over time advancement, there are two main patterns:

SkipTime pattern: Skip time to a specific point and verify state:

func (s *TimerTestSuite) TestSLABreach() {
    s.env.RegisterWorkflow(SLAMonitorWorkflow)
    s.env.RegisterActivity(CheckServiceHealthActivity)
    s.env.RegisterActivity(SendAlertActivity)

    healthCheckCount := 0
    alertSent := false

    s.env.OnActivity(CheckServiceHealthActivity, mock.Anything).
        Return(func(ctx context.Context) (bool, error) {
            healthCheckCount++
            // Service is healthy for first 5 checks, then goes down
            return healthCheckCount <= 5, nil
        })

    s.env.OnActivity(SendAlertActivity, mock.Anything, mock.Anything).
        Return(func(ctx context.Context, message string) error {
            alertSent = true
            return nil
        })

    // Register callback to check state after 1 hour (before SLA breach)
    s.env.RegisterDelayedCallback(func() {
        s.False(alertSent, "Alert should not be sent before SLA breach")
    }, 1*time.Hour)

    // Register callback to check state after 2 hours (after SLA breach)
    s.env.RegisterDelayedCallback(func() {
        s.True(alertSent, "Alert should be sent after SLA breach")
    }, 2*time.Hour)

    s.env.ExecuteWorkflow(SLAMonitorWorkflow)

    s.True(s.env.IsWorkflowCompleted())
}

FastForward pattern: Run workflow in discrete time steps:

func (s *TimerTestSuite) TestWorkflowInTimeSteps() {
    s.env.RegisterWorkflow(ProgressiveRetryWorkflow)
    s.env.RegisterActivity(AttemptOperationActivity)

    var attemptCount int
    var lastAttemptTime time.Time

    s.env.OnActivity(AttemptOperationActivity, mock.Anything, mock.Anything).
        Return(func(ctx context.Context, taskID string) error {
            attemptCount++
            lastAttemptTime = s.env.Now()
            if attemptCount < 3 {
                return errors.New("not ready yet")
            }
            return nil
        })

    // Run workflow step by step, advancing 5 minutes at a time
    started := false
    done := make(chan struct{})

    go func() {
        s.env.ExecuteWorkflow(ProgressiveRetryWorkflow, "task-steps")
        close(done)
    }()

    _ = started

    // In test environment, just execute - time advances automatically
    <-done

    s.Equal(3, attemptCount)
}

Testing Workflows with Multiple Concurrent Timers

Some workflows run multiple concurrent timers using workflow.NewTimer or workflow.Go:

func ParallelTimeoutWorkflow(ctx workflow.Context, taskID string) (string, error) {
    ao := workflow.ActivityOptions{
        StartToCloseTimeout: 30 * time.Second,
    }
    ctx = workflow.WithActivityOptions(ctx, ao)

    // Race between task completion and a timeout
    taskFuture := workflow.ExecuteActivity(ctx, SlowTaskActivity, taskID)
    timeoutTimer := workflow.NewTimer(ctx, 5*time.Minute)

    selector := workflow.NewSelector(ctx)

    var result string
    var err error

    selector.AddFuture(taskFuture, func(f workflow.Future) {
        err = f.Get(ctx, &result)
    })

    selector.AddFuture(timeoutTimer, func(f workflow.Future) {
        // Timer fired before task completed
        err = fmt.Errorf("task %s timed out after 5 minutes", taskID)
        result = "timeout"
    })

    selector.Select(ctx)
    return result, err
}

func (s *TimerTestSuite) TestParallelTimeoutWorkflowFastTask() {
    s.env.RegisterWorkflow(ParallelTimeoutWorkflow)
    s.env.RegisterActivity(SlowTaskActivity)

    // Mock the activity to complete quickly (before 5-minute timeout)
    s.env.OnActivity(SlowTaskActivity, mock.Anything, "fast-task").
        Return("task-completed", nil).
        After(1 * time.Minute) // Complete in 1 minute

    s.env.ExecuteWorkflow(ParallelTimeoutWorkflow, "fast-task")

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())

    var result string
    s.NoError(s.env.GetWorkflowResult(&result))
    s.Equal("task-completed", result)
}

func (s *TimerTestSuite) TestParallelTimeoutWorkflowSlowTask() {
    s.env.RegisterWorkflow(ParallelTimeoutWorkflow)
    s.env.RegisterActivity(SlowTaskActivity)

    // Mock the activity to take longer than the timeout
    s.env.OnActivity(SlowTaskActivity, mock.Anything, "slow-task").
        Return("task-completed", nil).
        After(10 * time.Minute) // Takes 10 minutes

    s.env.ExecuteWorkflow(ParallelTimeoutWorkflow, "slow-task")

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError()) // No workflow error, but timeout result

    var result string
    s.NoError(s.env.GetWorkflowResult(&result))
    s.Equal("timeout", result)
}

Testing Continue-As-New Workflows

Long-running workflows use ContinueAsNew to avoid history size limits:

const maxIterations = 100

type PerpetualWorkflowState struct {
    TotalProcessed int
    LastProcessedID string
}

func PerpetualBatchWorkflow(ctx workflow.Context, state PerpetualWorkflowState) error {
    ao := workflow.ActivityOptions{
        StartToCloseTimeout: 5 * time.Minute,
    }
    ctx = workflow.WithActivityOptions(ctx, ao)

    var batchResult BatchResult
    err := workflow.ExecuteActivity(ctx, ProcessNextBatchActivity, state.LastProcessedID).Get(ctx, &batchResult)
    if err != nil {
        return err
    }

    state.TotalProcessed += batchResult.ItemsProcessed
    state.LastProcessedID = batchResult.LastID

    if batchResult.HasMore {
        // Continue as new to avoid history bloat
        return workflow.NewContinueAsNewError(ctx, PerpetualBatchWorkflow, state)
    }

    return nil
}

func (s *TimerTestSuite) TestContinueAsNewWorkflow() {
    s.env.RegisterWorkflow(PerpetualBatchWorkflow)
    s.env.RegisterActivity(ProcessNextBatchActivity)

    callCount := 0

    s.env.OnActivity(ProcessNextBatchActivity, mock.Anything, mock.Anything).
        Return(func(ctx context.Context, lastID string) (BatchResult, error) {
            callCount++
            if callCount < 3 {
                return BatchResult{
                    ItemsProcessed: 10,
                    LastID:         fmt.Sprintf("item-%d", callCount*10),
                    HasMore:        true,
                }, nil
            }
            // Last batch
            return BatchResult{
                ItemsProcessed: 5,
                LastID:         "item-final",
                HasMore:        false,
            }, nil
        })

    initialState := PerpetualWorkflowState{}
    s.env.ExecuteWorkflow(PerpetualBatchWorkflow, initialState)

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())
    s.Equal(3, callCount)
}

Common Pitfalls

Forgetting to set test timeout: If your workflow can loop forever, ExecuteWorkflow will also loop forever in tests. Always set s.env.SetTestTimeout(duration) for workflows that might not terminate.

Real time in activities: Activity mocks run synchronously in tests, but if an activity mock uses time.Sleep, it delays real time, not simulated time. Never use time.Sleep in activity mocks—use the After option on the mock or design your test differently.

Callback timing with RegisterDelayedCallback: Callbacks registered with the same duration fire in the order they were registered, but activities completing in that window might fire before or after. Be careful about ordering assumptions.

Clock monotonicity: The test clock only moves forward. Once you've skipped past a time, you can't go back to check what happened before it. Capture state in callbacks as the workflow runs.

Temporal's time skipping makes previously untestable workflows—ones that sleep for days or run on cron schedules—completely testable in fast unit tests. The patterns here cover the most common scenarios; apply them consistently and your long-running workflow logic will be as well-tested as any other code.

Start now free