我的问题是在Spring boot中在Cron作业中执行一个方法。我在下面有一个名为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() {
 }

}
任务有一个停止时间,我想在超过最后期限时删除该任务。将从Cron job方法中检查时间,如下所示
@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);
}

下面是delete方法
@GetMapping("deleteTask")
public void deleteTask(@RequestParam long id, HttpServletResponse response) throws Exception {
    taskService.deleteTask(id);
    response.sendRedirect("/profile");
}

有了这些东西,我怎么能自动删除所有超过最后期限的任务?
提前谢谢!

最佳答案

为什么不使用这样的东西:

@Scheduled(cron = "0 * * * * ?")
public void scheduleTaskWithCronExpression() {
    DateTime currentT = dateTimeFormatter.format(LocalDateTime.now()));
    List<Task> tasks2beDeleted = taskService.expiredTasks(DateTime currentT);
    taskService.deleteAll(tasks2beDeleted);
}

注意事项:
您的存储库看起来很奇怪,它应该返回过期的任务,而不是时间。
您可以用db的now()方法实现expiredTasks
我不知道怎么做,但如果可以的话,你可以在数据库中实现一个过程
似乎您创建了一个使用repository的服务层,您还可以实现一个使用两个repository方法的服务方法,如taskService.deleteAllExpired();这似乎更好。

07-25 23:52
查看更多