Spring Boot
scheduled tasks
dynamic scheduling
Java
application development

How to dynamically turn on/off a scheduled method in a springboot application

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Spring Boot scheduled jobs are static by default, but real systems often need runtime control for maintenance windows, incident mitigation, or progressive feature rollout. A safe design has to handle thread safety, authorization, and cluster behavior, not just a boolean flag. The real question is whether you want to skip execution or stop scheduling entirely.

Pattern 1: Guard Execution with a Thread Safe Flag

The fastest implementation keeps @Scheduled timing static but skips job work when disabled.

java
1import java.util.concurrent.atomic.AtomicBoolean;
2import org.springframework.scheduling.annotation.Scheduled;
3import org.springframework.stereotype.Component;
4
5@Component
6public class BillingReconciliationJob {
7    private final AtomicBoolean enabled = new AtomicBoolean(true);
8
9    @Scheduled(fixedDelayString = "${jobs.billing.delay-ms:10000}")
10    public void run() {
11        if (!enabled.get()) {
12            return;
13        }
14        executeReconciliation();
15    }
16
17    public void setEnabled(boolean value) {
18        enabled.set(value);
19    }
20
21    public boolean isEnabled() {
22        return enabled.get();
23    }
24
25    private void executeReconciliation() {
26        System.out.println("Reconciliation job executed");
27    }
28}

This is simple and reliable when skipped triggers are acceptable and you do not need to stop the scheduler thread itself.

Expose an Admin Endpoint for Runtime Toggle

Wrap toggle access in a dedicated admin endpoint and secure it. Runtime job control without authorization is risky.

java
1import org.springframework.web.bind.annotation.*;
2
3@RestController
4@RequestMapping("/admin/jobs")
5public class JobAdminController {
6    private final BillingReconciliationJob job;
7
8    public JobAdminController(BillingReconciliationJob job) {
9        this.job = job;
10    }
11
12    @PostMapping("/billing/enabled/{value}")
13    public String setBillingJobEnabled(@PathVariable boolean value) {
14        job.setEnabled(value);
15        return "billing enabled=" + job.isEnabled();
16    }
17
18    @GetMapping("/billing/enabled")
19    public boolean getBillingJobEnabled() {
20        return job.isEnabled();
21    }
22}

Use role based access in Spring Security so only approved operators can toggle jobs.

Pattern 2: True Start and Stop Scheduling with TaskScheduler

If you need to stop scheduling itself, manage ScheduledFuture manually.

java
1import java.time.Duration;
2import java.util.concurrent.ScheduledFuture;
3import org.springframework.scheduling.TaskScheduler;
4import org.springframework.stereotype.Service;
5
6@Service
7public class DynamicJobManager {
8    private final TaskScheduler scheduler;
9    private ScheduledFuture<?> handle;
10
11    public DynamicJobManager(TaskScheduler scheduler) {
12        this.scheduler = scheduler;
13    }
14
15    public synchronized void start() {
16        if (handle == null || handle.isCancelled()) {
17            handle = scheduler.scheduleAtFixedRate(this::doWork, Duration.ofSeconds(10));
18        }
19    }
20
21    public synchronized void stop() {
22        if (handle != null) {
23            handle.cancel(false);
24        }
25    }
26
27    private void doWork() {
28        System.out.println("Dynamic job tick");
29    }
30}

This avoids wakeups when disabled and gives explicit lifecycle control.

Persist State Across Restarts

Runtime flags in memory are lost on deployment or restart. If toggle state must persist:

  • Store state in database, feature flag service, or configuration service.
  • Load state on startup and apply it before tasks run.
  • Log state changes with actor and timestamp.

Without persistence, teams may think a job is disabled while it restarts enabled after release.

Handle Multi Instance Deployments

In clustered environments, dynamic control must consider all instances. Disabling on one node is not enough if every node schedules the same task.

Common approaches:

  • Shared state plus periodic refresh.
  • Distributed lock for singleton job execution.
  • External scheduler orchestration where app receives work events.

Pick one clearly, document it, and test failover scenarios.

Add Observability and Operational Controls

Dynamic scheduling is operational logic, so expose telemetry:

  • Job enabled state metric.
  • Last run start and completion time.
  • Success and failure counters.
  • Last operator toggle event.

These signals reduce confusion during incidents and make runbook actions auditable.

Integration Testing Strategy

Test both functional and timing behavior. A useful integration flow:

  1. Enable job and verify execution counter increases.
  2. Disable job and verify counter stays constant.
  3. Re-enable and verify execution resumes.

Using deterministic test doubles for side effects makes these tests fast and reliable.

Common Pitfalls

  • Assuming @Scheduled annotations can be turned off dynamically without custom control logic.
  • Using non-thread-safe mutable fields for enable flags.
  • Exposing toggle APIs without authentication and authorization.
  • Ignoring in-flight run behavior when turning jobs off.
  • Missing cluster coordination, causing duplicate execution across instances.

Summary

  • Use an execution guard for simple runtime on or off behavior.
  • Use TaskScheduler and ScheduledFuture for true schedule lifecycle control.
  • Secure toggle paths and record audit events for operations.
  • Persist state when toggle decisions must survive restarts.
  • Design and test for multi-instance deployments to avoid duplicate runs.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.