javatimertask

how to set a task to run twice a day at specified times in Java


I have a java class that is a basic task that inherits from the TimerTask class.

public abstract class BasicTask extends TimerTask {

    private boolean taskBusy;

    protected synchronized boolean startTask() {
        if (taskBusy) {
            return false;
        }

        taskBusy = true;
        return true;
    }

    protected synchronized void stopTask() {
        taskBusy = false;
    }

    @Override
    public abstract void run();

}

Then I have some tasks that inherit from the basic task. for example class MyTask and I want MyTask to run twice a day at 9 and at 11.45.

code:

public class MyTask extends BasicTask {

    private long timePeriodBetweenRun;
    private Date firstExecutionDate;
    private Date firstExecutionDateSecond;
    private long timePeriodBetweenRunSecond;

    public MyTask (InputSource config, Timer timer){
        readConfig(config);
        timer.schedule(this, firstExecutionDate, timePeriodBetweenRun);
        //timer.schedule(this, firstExecutionDateSecond, timePeriodBetweenRunSecond); - I want to call sth like that but in this case it won't work 
    }
    @Override
    public void run() {
        try {
            if (!startTask()) {
                return;
            }
            doSth();
        } catch (Exception e) {
            LOG.error("Error " + e.getMessage(), e);
        } finally {
            stopTask();
        }
    }

Main class:

public class MainApp {

    public static void main(String[] args) {
        try {
            InputSource config = loadConfig();
            Timer myTimer= new Timer(false);
            new MyTask(config, myTimer);
        } catch (Exception e) {
            LOG.error("Unable to continue. " + e.getMessage(), e);
        }
    }

config file:

<myTask>
        <firstExecutionDate>2022-03-31 09:00:00</firstExecutionDate>
        <timePeriodBetweenRun>86400000</timePeriodBetweenRun>
</myTask>
<myTask>
        <firstExecutionDate>2022-03-31 11:45:00</firstExecutionDate>
        <timePeriodBetweenRun>86400000</timePeriodBetweenRun>
</myTask>

How to implement this?


Solution

  • You can use ScheduledExecutorService.