亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
問題 1:任務(wù)執(zhí)行時間長影響其他任務(wù)
問題 2:任務(wù)異常影響其他任務(wù)
① 任務(wù)超時執(zhí)行測試
② 任務(wù)異常測試
ScheduledExecutorService 小結(jié)
Home Java JavaBase Introducing the three simplest implementation methods of Java scheduled tasks

Introducing the three simplest implementation methods of Java scheduled tasks

Dec 29, 2020 pm 05:45 PM
java scheduled tasks

java基礎(chǔ)教程介紹定時任務(wù)在實際的開發(fā)

Introducing the three simplest implementation methods of Java scheduled tasks

推薦(免費):java基礎(chǔ)教程

日子匆匆穿過我而行,奔向海洋。

定時任務(wù)在實際的開發(fā)中特別常見,比如電商平臺 30 分鐘后自動取消未支付的訂單,以及凌晨的數(shù)據(jù)匯總和備份等,都需要借助定時任務(wù)來實現(xiàn),那么我們本文就來看一下定時任務(wù)最簡單的幾種實現(xiàn)方式。

TOP 1:Timer

Timer 是 JDK 自帶的定時任務(wù)執(zhí)行類,無論任何項目都可以直接使用 Timer 來實現(xiàn)定時任務(wù),所以 Timer 的優(yōu)點就是使用方便,它的實現(xiàn)代碼如下:

public?class?MyTimerTask?{
????public?static?void?main(String[]?args)?{
????????//?定義一個任務(wù)
????????TimerTask?timerTask?=?new?TimerTask()?{
????????????@Override
????????????public?void?run()?{
????????????????System.out.println("Run?timerTask:"?+?new?Date());
????????????}
????????};
????????//?計時器
????????Timer?timer?=?new?Timer();
????????//?添加執(zhí)行任務(wù)(延遲?1s?執(zhí)行,每?3s?執(zhí)行一次)
????????timer.schedule(timerTask,?1000,?3000);
????}
}

程序執(zhí)行結(jié)果如下:

Run?timerTask:Mon?Aug?17?21:29:25?CST?2020
Run?timerTask:Mon?Aug?17?21:29:28?CST?2020
Run?timerTask:Mon?Aug?17?21:29:31?CST?2020

Timer 缺點分析

Timer 類實現(xiàn)定時任務(wù)雖然方便,但在使用時需要注意以下問題。

問題 1:任務(wù)執(zhí)行時間長影響其他任務(wù)

當(dāng)一個任務(wù)的執(zhí)行時間過長時,會影響其他任務(wù)的調(diào)度,如下代碼所示:

public?class?MyTimerTask?{
????public?static?void?main(String[]?args)?{
????????//?定義任務(wù)?1
????????TimerTask?timerTask?=?new?TimerTask()?{
????????????@Override
????????????public?void?run()?{
????????????????System.out.println("進(jìn)入?timerTask?1:"?+?new?Date());
????????????????try?{
????????????????????//?休眠?5?秒
????????????????????TimeUnit.SECONDS.sleep(5);
????????????????}?catch?(InterruptedException?e)?{
????????????????????e.printStackTrace();
????????????????}
????????????????System.out.println("Run?timerTask?1:"?+?new?Date());
????????????}
????????};
????????//?定義任務(wù)?2
????????TimerTask?timerTask2?=?new?TimerTask()?{
????????????@Override
????????????public?void?run()?{
????????????????System.out.println("Run?timerTask?2:"?+?new?Date());
????????????}
????????};
????????//?計時器
????????Timer?timer?=?new?Timer();
????????//?添加執(zhí)行任務(wù)(延遲?1s?執(zhí)行,每?3s?執(zhí)行一次)
????????timer.schedule(timerTask,?1000,?3000);
????????timer.schedule(timerTask2,?1000,?3000);
????}
}

程序執(zhí)行結(jié)果如下:

進(jìn)入?timerTask?1:Mon?Aug?17?21:44:08?CST?2020
Run?timerTask?1:Mon?Aug?17?21:44:13?CST?2020
Run?timerTask?2:Mon?Aug?17?21:44:13?CST?2020
進(jìn)入?timerTask?1:Mon?Aug?17?21:44:13?CST?2020
Run?timerTask?1:Mon?Aug?17?21:44:18?CST?2020
進(jìn)入?timerTask?1:Mon?Aug?17?21:44:18?CST?2020
Run?timerTask?1:Mon?Aug?17?21:44:23?CST?2020
Run?timerTask?2:Mon?Aug?17?21:44:23?CST?2020
進(jìn)入?timerTask?1:Mon?Aug?17?21:44:23?CST?2020

從上述結(jié)果中可以看出,當(dāng)任務(wù) 1 運行時間超過設(shè)定的間隔時間時,任務(wù) 2 也會延遲執(zhí)行。 原本任務(wù) 1 和任務(wù) 2 的執(zhí)行時間間隔都是 3s,但因為任務(wù) 1 執(zhí)行了 5s,因此任務(wù) 2 的執(zhí)行時間間隔也變成了 10s(和原定時間不符)。

問題 2:任務(wù)異常影響其他任務(wù)

使用 Timer 類實現(xiàn)定時任務(wù)時,當(dāng)一個任務(wù)拋出異常,其他任務(wù)也會終止運行,如下代碼所示:

public?class?MyTimerTask?{
????public?static?void?main(String[]?args)?{
????????//?定義任務(wù)?1
????????TimerTask?timerTask?=?new?TimerTask()?{
????????????@Override
????????????public?void?run()?{
????????????????System.out.println("進(jìn)入?timerTask?1:"?+?new?Date());
????????????????//?模擬異常
????????????????int?num?=?8?/?0;
????????????????System.out.println("Run?timerTask?1:"?+?new?Date());
????????????}
????????};
????????//?定義任務(wù)?2
????????TimerTask?timerTask2?=?new?TimerTask()?{
????????????@Override
????????????public?void?run()?{
????????????????System.out.println("Run?timerTask?2:"?+?new?Date());
????????????}
????????};
????????//?計時器
????????Timer?timer?=?new?Timer();
????????//?添加執(zhí)行任務(wù)(延遲?1s?執(zhí)行,每?3s?執(zhí)行一次)
????????timer.schedule(timerTask,?1000,?3000);
????????timer.schedule(timerTask2,?1000,?3000);
????}
}

程序執(zhí)行結(jié)果如下:

進(jìn)入?timerTask?1:Mon?Aug?17?22:02:37?CST?2020
Exception?in?thread?"Timer-0"?java.lang.ArithmeticException:?/?by?zero
????at?com.example.MyTimerTask$1.run(MyTimerTask.java:21)
????at?java.util.TimerThread.mainLoop(Timer.java:555)
????at?java.util.TimerThread.run(Timer.java:505)
Process?finished?with?exit?code?0

Timer 小結(jié)

Timer 類實現(xiàn)定時任務(wù)的優(yōu)點是方便,因為它是 JDK 自定的定時任務(wù),但缺點是任務(wù)如果執(zhí)行時間太長或者是任務(wù)執(zhí)行異常,會影響其他任務(wù)調(diào)度,所以在生產(chǎn)環(huán)境下建議謹(jǐn)慎使用。

TOP 2:ScheduledExecutorService

ScheduledExecutorService 也是 JDK 1.5 自帶的 API,我們可以使用它來實現(xiàn)定時任務(wù)的功能,也就是說 ScheduledExecutorService 可以實現(xiàn) Timer 類具備的所有功能,并且它可以解決了 Timer 類存在的所有問題。

ScheduledExecutorService 實現(xiàn)定時任務(wù)的代碼示例如下:

public?class?MyScheduledExecutorService?{
????public?static?void?main(String[]?args)?{
????????//?創(chuàng)建任務(wù)隊列
????????ScheduledExecutorService?scheduledExecutorService?=
????????????????Executors.newScheduledThreadPool(10);?//?10?為線程數(shù)量
????????//?執(zhí)行任務(wù)
????????scheduledExecutorService.scheduleAtFixedRate(()?->?{
????????????System.out.println("Run?Schedule:"?+?new?Date());
????????},?1,?3,?TimeUnit.SECONDS);?//?1s?后開始執(zhí)行,每?3s?執(zhí)行一次
????}
}

程序執(zhí)行結(jié)果如下:

Run?Schedule:Mon?Aug?17?21:44:23?CST?2020
Run?Schedule:Mon?Aug?17?21:44:26?CST?2020
Run?Schedule:Mon?Aug?17?21:44:29?CST?2020

ScheduledExecutorService 可靠性測試

① 任務(wù)超時執(zhí)行測試

ScheduledExecutorService 可以解決 Timer 任務(wù)之間相應(yīng)影響的缺點,首先我們來測試一個任務(wù)執(zhí)行時間過長,會不會對其他任務(wù)造成影響,測試代碼如下:

public?class?MyScheduledExecutorService?{
????public?static?void?main(String[]?args)?{
????????//?創(chuàng)建任務(wù)隊列
????????ScheduledExecutorService?scheduledExecutorService?=
????????????????Executors.newScheduledThreadPool(10);
????????//?執(zhí)行任務(wù)?1
????????scheduledExecutorService.scheduleAtFixedRate(()?->?{
????????????System.out.println("進(jìn)入?Schedule:"?+?new?Date());
????????????try?{
????????????????//?休眠?5?秒
????????????????TimeUnit.SECONDS.sleep(5);
????????????}?catch?(InterruptedException?e)?{
????????????????e.printStackTrace();
????????????}
????????????System.out.println("Run?Schedule:"?+?new?Date());
????????},?1,?3,?TimeUnit.SECONDS);?//?1s?后開始執(zhí)行,每?3s?執(zhí)行一次
????????//?執(zhí)行任務(wù)?2
????????scheduledExecutorService.scheduleAtFixedRate(()?->?{
????????????System.out.println("Run?Schedule2:"?+?new?Date());
????????},?1,?3,?TimeUnit.SECONDS);?//?1s?后開始執(zhí)行,每?3s?執(zhí)行一次
????}
}

程序執(zhí)行結(jié)果如下:

Run?Schedule2:Mon?Aug?17?11:27:55?CST?2020
進(jìn)入?Schedule:Mon?Aug?17?11:27:55?CST?2020
Run?Schedule2:Mon?Aug?17?11:27:58?CST?2020
Run?Schedule:Mon?Aug?17?11:28:00?CST?2020
進(jìn)入?Schedule:Mon?Aug?17?11:28:00?CST?2020
Run?Schedule2:Mon?Aug?17?11:28:01?CST?2020
Run?Schedule2:Mon?Aug?17?11:28:04?CST?2020

從上述結(jié)果可以看出,當(dāng)任務(wù) 1 執(zhí)行時間 5s 超過了執(zhí)行頻率 3s 時,并沒有影響任務(wù) 2 的正常執(zhí)行,因此使用 ScheduledExecutorService 可以避免任務(wù)執(zhí)行時間過長對其他任務(wù)造成的影響。

② 任務(wù)異常測試

接下來我們來測試一下 ScheduledExecutorService 在一個任務(wù)異常時,是否會對其他任務(wù)造成影響,測試代碼如下:

public?class?MyScheduledExecutorService?{
????public?static?void?main(String[]?args)?{
????????//?創(chuàng)建任務(wù)隊列
????????ScheduledExecutorService?scheduledExecutorService?=
????????????????Executors.newScheduledThreadPool(10);
????????//?執(zhí)行任務(wù)?1
????????scheduledExecutorService.scheduleAtFixedRate(()?->?{
????????????System.out.println("進(jìn)入?Schedule:"?+?new?Date());
????????????//?模擬異常
????????????int?num?=?8?/?0;
????????????System.out.println("Run?Schedule:"?+?new?Date());
????????},?1,?3,?TimeUnit.SECONDS);?//?1s?后開始執(zhí)行,每?3s?執(zhí)行一次
????????//?執(zhí)行任務(wù)?2
????????scheduledExecutorService.scheduleAtFixedRate(()?->?{
????????????System.out.println("Run?Schedule2:"?+?new?Date());
????????},?1,?3,?TimeUnit.SECONDS);?//?1s?后開始執(zhí)行,每?3s?執(zhí)行一次
????}
}

程序執(zhí)行結(jié)果如下:

進(jìn)入?Schedule:Mon?Aug?17?22:17:37?CST?2020
Run?Schedule2:Mon?Aug?17?22:17:37?CST?2020
Run?Schedule2:Mon?Aug?17?22:17:40?CST?2020
Run?Schedule2:Mon?Aug?17?22:17:43?CST?2020

從上述結(jié)果可以看出,當(dāng)任務(wù) 1 出現(xiàn)異常時,并不會影響任務(wù) 2 的執(zhí)行。

ScheduledExecutorService 小結(jié)

在單機(jī)生產(chǎn)環(huán)境下建議使用 ScheduledExecutorService 來執(zhí)行定時任務(wù),它是 JDK 1.5 之后自帶的 API,因此使用起來也比較方便,并且使用 ScheduledExecutorService 來執(zhí)行任務(wù),不會造成任務(wù)間的相互影響。

TOP 3:Spring Task

如果使用的是 Spring 或 Spring Boot 框架,可以直接使用 Spring Framework 自帶的定時任務(wù),使用上面兩種定時任務(wù)的實現(xiàn)方式,很難實現(xiàn)設(shè)定了具體時間的定時任務(wù),比如當(dāng)我們需要每周五來執(zhí)行某項任務(wù)時,但如果使用 Spring Task 就可輕松的實現(xiàn)此需求。

以 Spring Boot 為例,實現(xiàn)定時任務(wù)只需兩步:

  1. 開啟定時任務(wù);
  2. 添加定時任務(wù)。

具體實現(xiàn)步驟如下。

① 開啟定時任務(wù)

開啟定時任務(wù)只需要在 Spring Boot 的啟動類上聲明 @EnableScheduling?即可,實現(xiàn)代碼如下:

@SpringBootApplication
@EnableScheduling?//?開啟定時任務(wù)
public?class?DemoApplication?{
????//?do?someing
}

② 添加定時任務(wù)

定時任務(wù)的添加只需要使用 @Scheduled?注解標(biāo)注即可,如果有多個定時任務(wù)可以創(chuàng)建多個 @Scheduled 注解標(biāo)注的方法,示例代碼如下:

import?org.springframework.scheduling.annotation.Scheduled;
import?org.springframework.stereotype.Component;

@Component?//?把此類托管給?Spring,不能省略
public?class?TaskUtils?{
????//?添加定時任務(wù)
????@Scheduled(cron?=?"59?59?23?0?0?5")?//?cron?表達(dá)式,每周五?23:59:59?執(zhí)行
????public?void?doTask(){
????????System.out.println("我是定時任務(wù)~");
????}
}

注意:定時任務(wù)是自動觸發(fā)的無需手動干預(yù),也就是說 Spring Boot 啟動后會自動加載并執(zhí)行定時任務(wù)。

Cron 表達(dá)式

Spring Task 的實現(xiàn)需要使用 cron 表達(dá)式來聲明執(zhí)行的頻率和規(guī)則,cron 表達(dá)式是由 6 位或者 7 位組成的(最后一位可以省略),每位之間以空格分隔,每位從左到右代表的含義如下:
Introducing the three simplest implementation methods of Java scheduled tasks

其中 * 和 ? 號都表示匹配所有的時間。

Introducing the three simplest implementation methods of Java scheduled tasks
cron 表達(dá)式在線生成地址:https://cron.qqe2.com/

The above is the detailed content of Introducing the three simplest implementation methods of Java scheduled tasks. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

See all articles