@Entity
@Table(name = "tasks")
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "deadline")
private LocalDateTime deadline;
@Column(name = "status")
private Integer status;
// Getters and setters
}
@Repository
public interface TaskRepository extends JpaRepository<Task, Long> {
List<Task> findByDeadlineBeforeAndStatus(Integer status, LocalDateTime deadline);
}
@Component
public class TaskScheduler {
@Autowired
private TaskRepository taskRepository;
@Scheduled(cron = "0 0 * * * *") // 每小时执行一次
public void updateTaskStatus() {
LocalDateTime now = LocalDateTime.now();
List<Task> tasks = taskRepository.findByDeadlineBeforeAndStatus(0, now);
for (Task task : tasks) {
task.setStatus(1);
taskRepository.save(task);
}
}
}
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
这样,定时任务就会每小时检查一次数据库中的任务,如果有任务的截止时间早于当前时间且状态为0,它们的状态将被更新为1。你可以根据实际需要调整定时任务的执行频率和查询条件。