How to set up a daily scheduled task at a specific time in Java?

In Java, you can set up scheduled tasks using the java.util.Timer and java.util.TimerTask classes. Here is an example demonstrating how to execute a task at a specific time every day.

import java.util.Timer;
import java.util.TimerTask;
import java.util.Calendar;

public class DailyTaskScheduler {
    public static void main(String[] args) {
        // 创建一个定时器对象
        Timer timer = new Timer();

        // 创建一个 TimerTask 对象
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // 在这里编写需要执行的任务代码
                System.out.println("执行每天固定时间任务");
            }
        };

        // 获取当前时间
        Calendar calendar = Calendar.getInstance();

        // 设置定时任务的时间,例如每天的14:30:00执行
        calendar.set(Calendar.HOUR_OF_DAY, 14);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);

        // 如果设定的时间比当前时间早,则在第二天的相同时间执行任务
        if (calendar.getTime().compareTo(Calendar.getInstance().getTime()) < 0) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        // 开始定时任务,每天固定时间执行一次
        timer.schedule(task, calendar.getTime(), 24 * 60 * 60 * 1000);
    }
}

In the example mentioned above, we first created a Timer object and a TimerTask object, then set the timing of the task using the Calendar class. By comparing the current time with the set time, if the set time is earlier than the current time, the task will be scheduled to run at the same time the following day. Finally, we used the schedule method of Timer to specify the execution time and interval of the task. In this example, the task will run at the same fixed time every day.

广告
Closing in 10 seconds
bannerAds