国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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("進入?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é)果如下:

進入?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
進入?timerTask?1:Mon?Aug?17?21:44:13?CST?2020
Run?timerTask?1:Mon?Aug?17?21:44:18?CST?2020
進入?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
進入?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("進入?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é)果如下:

進入?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("進入?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
進入?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
進入?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("進入?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é)果如下:

進入?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é)

在單機生產(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?表達式,每周五?23:59:59?執(zhí)行
????public?void?doTask(){
????????System.out.println("我是定時任務(wù)~");
????}
}

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

Cron 表達式

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

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

Introducing the three simplest implementation methods of Java scheduled tasks
cron 表達式在線生成地址: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
1502
276
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.

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

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

See all articles