每天触发一次方法

时间:2016-03-07 22:28:24

标签: java

我希望每天触发一次方法。我已经尝试使用Timer和TimerTask进行调度,但我的问题是该程序可能每天运行几次,有一天可能没有。如何在程序首次启动时检查该方法是否已在当天运行?

谢谢!

4 个答案:

答案 0 :(得分:1)

使用cron job安排所选方法

例如0 20 ***这是每天20:00时的时钟

答案 1 :(得分:0)

查看Java Date Class。这样,您可以保存程序在文件中运行的最后一次,然后再次运行,读取当前日期并查看当天是否更改。

答案 2 :(得分:0)

我过去使用过Quartz Scheduler:https://quartz-scheduler.org/

答案 3 :(得分:0)

如果您使用的是弹簧,则可以使用良好的抽象来触发方法:

@Configuration
@EnableAsync
@EnableScheduling
public class AppConfig {
}

我建议使用数据库同步应用的多个实例之间的每日运行:

@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
    Connection conn = ...
    String sql= "select lastrun from runs where method = 'doSomething' for update";
    PreparedStatement ps = conn.prepareStatement(sql,ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
        if(rs.getDate(1)/* is more than 23 hours ago*/){
            //do your work here....
            rs.updateDate(1, new Date());
            rs.updateRow();
        }
    } else{
        //todo
    }
    //todo: make sure rs, ps, and conn get closed...
}

来源:http://blog.udby.com/archives/15http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support

相关问题