Home  >  Article  >  Java  >  How to set a timer for daily scheduled task execution in Java?

How to set a timer for daily scheduled task execution in Java?

PHPz
PHPzOriginal
2023-12-27 11:10:241280browse

How to set a timer for daily scheduled task execution in Java?

Java timer: How to set a scheduled execution task every day?

In daily Java development, we often encounter the need to perform a certain task regularly every day. For example, perform a data backup task at 1 a.m. every day, or send a daily email at 8 p.m., etc. So in Java, we can use timers to achieve such a function.

Java provides a variety of timer implementation methods. This article will introduce two ways to set up daily scheduled execution tasks based on Timer and ScheduledExecutorService, and provide specific code examples.

1. Use the Timer class to implement scheduled tasks every day

The Timer class is a simple timer class provided by Java, which can be used to perform scheduled tasks. We can use the schedule method of the Timer class to set up scheduled execution of tasks every day, and use the Date class to specify the time point at which the task should be executed.

The following is a code example that uses the Timer class to implement scheduled tasks every day:

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

public class DailyTaskWithTimer {
    public static void main(String[] args) {
        Timer timer = new Timer();
        
        // 设置任务执行的时间(每天的定时时间)
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 1); // 设置时
        calendar.set(Calendar.MINUTE, 0);      // 设置分
        calendar.set(Calendar.SECOND, 0);      // 设置秒
        
        // 如果当前时间已经过了设定的定时时间,则将定时时间推迟到明天
        if (calendar.getTime().before(new Date())) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        
        // 执行任务
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // TODO: 需要执行的任务逻辑
            }
        }, calendar.getTime(), 24 * 60 * 60 * 1000); // 24小时执行一次
    }
}

In the above code, we set the task execution time through the Calendar class. It should be noted that if the current time If the set timing time has passed, the timing time will be postponed to tomorrow. Then use the schedule method of Timer to execute the task. The first parameter is a TimerTask object, which defines the task logic that needs to be executed. The second parameter is the start execution time of the task, and the third parameter is the interval time of the task. Here Set to execute every 24 hours.

2. Use ScheduledExecutorService to implement scheduled execution of tasks every day

ScheduledExecutorService is an advanced timer provided by Java, which provides a more flexible and reliable way to execute scheduled tasks. We can use the scheduleAtFixedRate method of ScheduledExecutorService to implement scheduled execution of tasks every day.

The following is a code example that uses ScheduledExecutorService to implement scheduled execution of tasks every day:

import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DailyTaskWithScheduledExecutor {
    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        
        // 设置任务执行的时间(每天的定时时间)
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 1); // 设置时
        calendar.set(Calendar.MINUTE, 0);      // 设置分
        calendar.set(Calendar.SECOND, 0);      // 设置秒
        
        // 如果当前时间已经过了设定的定时时间,则将定时时间推迟到明天
        if (calendar.getTime().before(new Date())) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        
        // 执行任务
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // TODO: 需要执行的任务逻辑
            }
        }, calendar.getTimeInMillis() - System.currentTimeMillis(), 24 * 60 * 60 * 1000, TimeUnit.MILLISECONDS); // 24小时执行一次
        
        // 关闭定时器
        //executorService.shutdown();
    }
}

In the above code, we set the task execution time through the Calendar class. It should be noted that if the current time has already After the set timing time has passed, the timing time will be postponed to tomorrow. Then use the scheduleAtFixedRate method of ScheduledExecutorService to execute the task. The first parameter is a Runnable object, which defines the task logic that needs to be executed. The second parameter is the initial delay time of the task. The difference calculated here is the current set time. The difference from the current time. The third parameter is the execution interval of the task, which is set to be executed every 24 hours. The fourth parameter is the time unit, which is set to milliseconds. Because ScheduledExecutorService is a thread pool, we also need to manually close the thread pool after the task is executed.

Summary:

This article introduces two ways to set up daily scheduled execution tasks in Java: using the Timer and ScheduledExecutorService classes. Both methods can implement the function of executing tasks regularly every day. Developers can choose an appropriate method to schedule scheduled tasks based on actual needs.

The above is the detailed content of How to set a timer for daily scheduled task execution in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn