user6031489
user6031489

Reputation:

Trigger method once every day

I'm looking to trigger a method once every day. I've tried scheduling this with Timer and TimerTask, but my problem is that the program may be run several times a day, and somedays maybe none. How can I when the program first starts check if the method already has been run that day?

Thanks!

Upvotes: 1

Views: 333

Answers (4)

Andreas
Andreas

Reputation: 5103

If you are using spring, there are good abstractions to trigger a method:

@Configuration
@EnableAsync
@EnableScheduling
public class AppConfig {
}

I would suggest using a database to synchronize daily runs between multiple instances of your app:

@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...
}

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

Upvotes: 0

Waz Au
Waz Au

Reputation: 21

I've used Quartz Scheduler in the past: https://quartz-scheduler.org/

Upvotes: 0

kakashi hatake
kakashi hatake

Reputation: 1185

Use cron job with scheduling your selected method

For example 0 20 *** this do every day clock when 20:00

Upvotes: 1

FMaz
FMaz

Reputation: 394

Take a look into the Java Date Class. That way you can save the last time your program was run in a file and then once it is run again read the current date and see if the day changed.

Upvotes: 0

Related Questions