我的问题是关于在Spring启动时在Cron Job中执行方法。我下面有一个名为 Task 的类
@Entity
@Table(name = "task", schema = "public")
public class Task {
@Id
@GeneratedValue
private Long id;
@NotEmpty
private String date;
@NotEmpty
private String startTime;
@NotEmpty
private String stopTime;
@NotEmpty
@Column(length=1000)
private String description;
@ManyToOne
@JoinColumn(name="USER_EMAIL")
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getStopTime() {
return stopTime;
}
public void setStopTime(String stopTime) {
this.stopTime = stopTime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Task(String date, String startTime, String stopTime, String description, User user) {
this.date = date;
this.startTime = startTime;
this.stopTime = stopTime;
this.description = description;
this.user = user;
}
public Task(String date, String startTime, String stopTime, String description) {
this.date = date;
this.startTime = startTime;
this.stopTime = stopTime;
this.description = description;
}
public Task() {
}
}
任务有一个 stopTime ,我想在截止日期过后删除该任务。时间将通过 Cron作业方法进行检查,如下所示
@Scheduled(cron = "0 * * * * ?")
public void scheduleTaskWithCronExpression() {
logger.info("Cron Task :: Execution Time - {}", dateTimeFormatter.format(LocalDateTime.now()));
}
比在TaskRepository中创建的查询要花费所有任务的截止时间
public interface TaskRepository extends JpaRepository<Task, Long> {
@Modifying
@Query("select stopTime from Task ")
ZonedDateTime showEndTimeTasks(ZonedDateTime stopTime);
}
这是删除方法
@GetMapping("deleteTask")
public void deleteTask(@RequestParam long id, HttpServletResponse response) throws Exception {
taskService.deleteTask(id);
response.sendRedirect("/profile");
}
有了这些东西,我如何自动删除所有超过期限的任务? 预先感谢!
答案 0 :(得分:0)
为什么不使用这样的东西:
@Scheduled(cron = "0 * * * * ?")
public void scheduleTaskWithCronExpression() {
DateTime currentT = dateTimeFormatter.format(LocalDateTime.now()));
List<Task> tasks2beDeleted = taskService.expiredTasks(DateTime currentT);
taskService.deleteAll(tasks2beDeleted);
}
一些注意事项: