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

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

Dec 27, 2023 am 11:10 AM
javatimerExecuted every day

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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor