Skip to main content

4. Implement scheduling task

Trong phần này, chúng ta sẽ tìm hiểu cách triển khai tác vụ lập lịch trong ứng dụng Spring Boot của chúng ta. Tác vụ lập lịch cho phép chúng ta thực hiện các công việc định kỳ mà không cần phải can thiệp thủ công.

Cấu hình


import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
public class SchedulingConfig {
}

Áp dụng

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {
@Scheduled(fixedRate = 10000) // Run every 10 seconds
public void performScheduledTask() {
System.out.println("⏰ Scheduled task executed at: " + System.currentTimeMillis());
// Simulate task
}

@Scheduled(cron = "0 0 12 * * ?") // Run every day at 12PM
public void dailyTask() {
System.out.println("⏰ Daily task executed at 12 PM.");
}
}

Kết luận

Việc dùng @Scheduled trong Spring Boot giúp chúng ta dễ dàng triển khai các tác vụ lập lịch mà không cần phải can thiệp thủ công. Chúng ta có thể định nghĩa các tác vụ này bằng cách sử dụng các annotation đơn giản và cấu hình thời gian thực hiện một cách linh hoạt.