1. What is Scheduling?
Scheduling means running a task automatically at a fixed time or interval without any user action.
Examples:
Run every 10 seconds
Run every 1 minute
Run daily at 2 AM
2. Why Scheduling is Used (Real Projects)
Database sync (legacy → new system)
Cleanup old records
Email / notification jobs
3. How Spring Boot Scheduler Works (Flow)
Application Starts
↓
@EnableScheduling detected
↓
Spring scans @Scheduled methods
↓
Scheduler thread executes methods
4. Required Annotations
4.1 @EnableScheduling
@EnableScheduling
Purpose:
Activates scheduler support in Spring Boot
4.2 @Scheduled
@Scheduled(fixedRate = 10000)
Purpose:
Marks a method to run automatically
5. Basic Scheduler Setup
5.1 Main Class
@SpringBootApplication
@EnableScheduling
public class SchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulerApplication.class, args);
}
}
5.2 Scheduler Class
@Component
public class SimpleScheduler {
@Scheduled(fixedRate = 5000)
public void runTask() {
System.out.println("Task running every 5 seconds");
}
}
6. Scheduler Types
6.1 fixedRate Scheduler
@Scheduled(fixedRate = 10000)
public void fixedRateJob() {
System.out.println("Runs every 10 seconds");
}
Meaning:
Runs every 10 seconds
Time counted from start of previous execution
6.2 fixedDelay Scheduler
@Scheduled(fixedDelay = 10000)
public void fixedDelayJob() {
System.out.println("Runs 10 seconds after last execution finishes");
}
Meaning:
Waits 10 seconds after method completes
6.3 initialDelay Scheduler
@Scheduled(initialDelay = 5000, fixedRate = 15000)
public void delayedJob() {
System.out.println("Starts after 5 seconds, runs every 15 seconds");
}
7. Cron Scheduler (Most Important)
7.1 Cron Format
second minute hour day month weekday
7.2 Cron Example
@Scheduled(cron = "0 */1 * * * *")
public void cronJob() {
System.out.println("Runs every 1 minute");
}
7.3 Common Cron Expressions
| Requirement | Cron |
|---|---|
| Every 10 sec | */10 * * * * * |
| Every minute | 0 * * * * * |
| Every 5 min | 0 */5 * * * * |
| Daily 9 AM | 0 0 9 * * * |
| Daily 2 AM | 0 0 2 * * * |
8. Scheduler Rules (Very Important)
Scheduler method MUST:
Be public
Return void
Have no parameters
Scheduler method SHOULD NOT:
Be static
Accept request parameters
9. Database Example – MySQL Old Data
9.1 Table
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
synced BOOLEAN DEFAULT FALSE
);
9.2 Entity
@Entity
@Table(name = "users")
public class OldUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private boolean synced;
}
9.3 Repository
public interface OldUserRepository extends JpaRepository<OldUser, Long> {
List<OldUser> findBySyncedFalse();
}
10. Scheduler + Remote API Example (Real World)
@Component
public class DataSyncScheduler {
@Autowired
private OldUserRepository repository;
private final RestTemplate restTemplate = new RestTemplate();
private static final String REMOTE_API = "https://remote-system/api/users";
@Scheduled(cron = "0 */1 * * * *")
public void sendDataToRemoteSystem() {
List<OldUser> users = repository.findBySyncedFalse();
for (OldUser user : users) {
try {
Map<String, Object> body = new HashMap<>();
body.put("name", user.getName());
ResponseEntity<String> response =
restTemplate.postForEntity(REMOTE_API, body, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
user.setSynced(true);
repository.save(user);
}
} catch (Exception e) {
System.out.println("Failed to sync user: " + user.getId());
}
}
}
}
11. Scheduler Execution Timeline
App Start
↓
Wait for cron time
↓
Fetch unsynced data
↓
Send to remote API
↓
Update synced flag
12. Production Best Practices
Use batch size (example: 100 records)
13. Summary
Scheduler runs automatically
Best for background jobs
✅ This material is suitable for:
0 Comments