在CRON JOBS内部执行方法

时间:2018-12-05 20:39:08

标签: spring postgresql hibernate spring-boot cron

我的问题是关于在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");
}

有了这些东西,我如何自动删除所有超过期限的任务? 预先感谢!

1 个答案:

答案 0 :(得分:0)

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

@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
  • 我不知道如何,但是如果可以的话,您可以在数据库中实现一个过程
  • 似乎您已经建立了一个使用存储库的服务层,您还可以实现一个使用两个存储库方法的服务方法,例如taskService.deleteAllExpired();。似乎更好。