Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize timing tasks in Java stand-alone environment

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to achieve timing tasks in Java stand-alone environment". The editor shows you the operation process through actual cases. The operation method is simple, fast and practical. I hope this article "how to achieve timing tasks in Java stand-alone environment" can help you solve the problem.

Timed task framework

TimeTask

From the beginning of learning java, the first time to implement scheduled tasks is to use TimeTask. The class of Timer uses TaskQueue to store scheduled tasks, which is a priority queue based on the minimum heap implementation. TaskQueue sorts tasks according to the time between them and the next execution time, ensuring that the tasks at the top of the stack are executed first.

Example code:

Public static void main (String [] args) {TimerTask task = new TimerTask () {public void run () {System.out.println ("current time:" + new Date () + "n" + "thread name:" + Thread.currentThread (). GetName ());}} Timer timer = new Timer ("Timer"); long delay = 5000L; timer.schedule (task, delay); System.out.println ("current time:" + new Date () + "n" + "thread name:" + Thread.currentThread (). GetName ());}

Running result:

Current time: Wed Apr 06 22:05:04 CST 2022n thread name: main current time: Wed Apr 06 22:05:09 CST 2022n thread name: Timer

As can be seen from the results, the timing task was performed 5 seconds later.

Disadvantages:

TimeTask tasks can only be executed serially. Once one task is executed for a long time, it will affect the execution of other tasks.

If an exception occurs during the execution of the task, the task will stop directly.

With the passage of time, the technology of java is also constantly updated. In view of the shortcomings of TimeTask, ScheduledExecutorService appears to replace TimeTask.

ScheduledExecutorService

ScheduledExecutorService is an interface with multiple implementation classes, the more common of which is ScheduledThreadPoolExecutor. ScheduledThreadPoolExecutor itself is a thread pool, which internally uses DelayQueue as the task queue and supports task execution concurrently.

Example code:

Public static void main (String [] args) throws InterruptedException {ScheduledExecutorService executorService = Executors.newScheduledThreadPool (3); / / execute task: execute executorService.scheduleAtFixedRate (()-> {System.out.println ("execute task:" + new Date () + ", thread name:" + Thread.currentThread (). GetName ());}, 1,10, TimeUnit.SECONDS);}

Disadvantages:

Try to avoid using Executors to create a thread pool, because the queues used inside the jdk built-in thread pool are relatively large, so it is easy to produce OOM.

Scheduled tasks are based on JVM stand-alone memory, and the scheduled tasks disappear as soon as they are restarted.

Cannot support cron expressions to implement rich scheduled tasks.

Spring Task

After learning Spring, I began to use the Task that comes with Spring. Spring Framework comes with timing tasks and provides cron expressions to achieve rich timing task configuration.

Example code:

@ EnableScheduling@Componentpublic class SpringTask {private Logger logger = LoggerFactory.getLogger (SpringTask.class); private static final SimpleDateFormat dateFormat = new SimpleDateFormat ("HH:mm:ss"); / * * fixedRate: execute at a fixed rate. Execute every 5 seconds. * / @ Scheduled (fixedRate = 5000) public void invokeTaskWithFixedRate () {logger.info ("FixedRate Task: Current Time is {}", dateFormat.format (new Date ();} / * * fixedDelay: fixed delay. It was executed 2 seconds after the last call was successful. * / @ Scheduled (fixedDelay = 2000) public void invokeTaskWithFixedDelay () {try {TimeUnit.SECONDS.sleep (3); logger.info ("FixedDelay Task: Current Time is {}", dateFormat.format (new Date ());} catch (InterruptedException e) {logger.error ("invoke task error", e) }} / * initialDelay: initial delay The first execution of the task will be delayed by 5 seconds, and then will be executed at fixed intervals of 5 seconds. * / @ Scheduled (initialDelay = 5000, fixedRate = 5000) public void invokeTaskWithInitialDelay () {logger.info ("Task with InitialDelay: Current Time is {}", dateFormat.format (new Date ();} / * * cron: use the Cron expression to execute * / @ Scheduled every 5 seconds (cron = "0ram 5 *?") Public void invokeTaskWithCron_Expression () {logger.info ("Task Cron Expression: Current Time is {}", dateFormat.format (new Date ();}}

Execution result:

2022-04-06 23 com.fw.task.SpringTask 06 INFO 20.945 14604-[scheduling-1] com.fw.task.SpringTask: Task Cron Expression: Current Time is 23:06:20

2022-04-06 23 com.fw.task.SpringTask 06 INFO 22.557 14604-[scheduling-1] com.fw.task.SpringTask: Task with Initial Delay: Current Time is 23:06:22

2022-04-06 23 com.fw.task.SpringTask 06 INFO 22.557 14604-[scheduling-1] com.fw.task.SpringTask: Fixed Rate Task: Current Time is 23:06:22

2022-04-06 23 com.fw.task.SpringTask 06 INFO 25.955 14604-[scheduling-1] com.fw.task.SpringTask: Fixed Delay Task: Current Time is 23:06:25

2022-04-06 23 com.fw.task.SpringTask 06 INFO 25.955 14604-[scheduling-1] com.fw.task.SpringTask: Task Cron Expression: Current Time is 23:06:25

2022-04-06 23 com.fw.task.SpringTask 06Parade 27.555 INFO 14604-[scheduling-1] com.fw.task.SpringTask: Task with Initial Delay: Current Time is 23:06:27

2022-04-06 23 com.fw.task.SpringTask 06Parade 27.556 INFO 14604-[scheduling-1] com.fw.task.SpringTask: Fixed Rate Task: Current Time is 23:06:27

@ EnableScheduling needs to start the timing task, @ Scheduled (cron = "0tica5 *?") Configure rules for scheduled tasks. Cron expressions support rich timed task configurations, and unfamiliar ones can be viewed.

Advantages:

Easy to use and support a variety of complex scheduled task configurations

Disadvantages:

Based on the stand-alone timing task, once the timing task is restarted, it disappears.

Scheduled tasks default to single-thread execution, and @ EnableAsync needs to be enabled if parallel execution is needed.

There is no unified graphical task scheduling management, and scheduled tasks cannot be controlled.

This is the end of the content about "how to achieve scheduled tasks in the Java stand-alone environment". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report