如何在 Java 中的指定时间将任务设置为每天两次 运行

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

我有一个 java class 是从 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();

}

然后我有一些继承自基本任务的任务。 例如 class MyTask,我希望 MyTask 在 9 点和 11.45 每天两次 运行。

代码:

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();
        }
    }

主要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);
        }
    }

配置文件:

<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>

如何实现?

您可以使用 ScheduledExecutorService.