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 use Timer timer in java

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Xiaobian to share with you how to use the Timer in java, I believe most people still do not know how to use it, so share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!

Timer Usage and Start-up 1. Overview

Timed scheduling task function is mainly used in Java Timer object, which is processed internally using multithreading, so it and multithreading technology still have a very large association. In JDK Timer class is mainly responsible for scheduling tasks, that is, in the specified time to start executing a task, but the class encapsulating the task is TimerTask class.

2. application scenarios

When we use timer, there are generally four situations:

Specify time to execute

Repeat execution at specified intervals after execution at specified times

How long after mission initiation?

How long after the task is started, how long after execution, specify the interval to repeat execution

3. use method

First of all, we need to customize the task to be executed by inheriting the TimerTask class and implementing the run() method (of course, we can also write anonymous inner classes).

You need to create a timer (Timer class object) and execute the time-running task via the Timer.schedule(TimerTask task,Date time) method

The specific codes are as follows:

package timerdemo; import java.util.Timer;import java.util.TimerTask; public class TimerDemo { public static void main(String[] args) { timerTest(); } public static void timerTest(){ //create a timer Timer timer = new Timer(); //schedule method is a method for executing time-timed tasks timer.schedule(new TimerTask() { The//run method is a specific task that needs to be executed regularly @Override public void run() { System.out.println("timer test!!! "); } }, 1000, 10000); }}

There are four schedule methods, which correspond to the four cases mentioned above:

4. starting method

1. Start under jar project

Make jar project into jar package and run it through java -jar timer. jar

2.这web工程下启动

spring中我们可以通过实现接口ApplicationListener,并重写public void onApplicationEvent(ApplicationEvent event) {}可以在容器初始话的时候执行这个方法

下面展示下web工程下每天00:00执行任务的代码:

@Componentpublic class SystemInitListener implements ApplicationListener { @Override public void onApplicationEvent(ContextRefreshedEvent event) { //创建定时器 Timer timer = new Timer(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE,1); calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DATE),0,0,0); long timeInterval = 24 * 60 * 60 * 1000; timer.schedule(new TimerTask() { @Override public void run() { // 每天00:00需要做的事情 } }, calendar.getTime(), timeInterval);java的几种定时器小结

总结一下我使用过的4种类型的定时器:@Scheduled注解、quartz、new Timer().schedule、使用线程控制。

1.@Scheduled注解

@Scheduled注解是最简单的方式,只需要启用定时器,在方法上添加注解即可。

在spring配置中加入:

在要具体的方法上加入注解@Scheduled

@Scheduled(cron = "0 0 * * * ? ") public void myTask(){ //定时任务......}2.quartz

quartz使用的是可配置的方式,将所有的定时器都配置再一个xml文件里面。

步骤如下:

1.创建一个spring的配置文件:spring-quartz.xml

2.定义工作任务的job

3.定义触发器Trigger并与job绑定

4.定义调度器,并将Trigger注册到scheduler

最后记得将xml写入web.xml里!

contextConfigLocation classpath:applicationContext.xml, classpath:log4j.xml, classpath:spring-quartz.xml 3.使用Timer

使用Timer的schedule,schedule有3个参数:

schedule(TimerTask task, long delay, long period)

第一个为定时任务,根据业务需要重写TimerTask的run方法即可;

第二个为延时启动,单位毫秒;

第三个位多久运行一次,单位毫秒;

new Timer().schedule(new TimerTask() { @Override public void run() { try { //do Something } catch (Exception e) { e.printStackTrace(); } } },0,5L * 60 * 1000);4.使用线程控制

使用线程来控制就更灵活一些,可以根据自己的需要判断什么时候运行,什么时候停止,这需要对java的线程有一定的了解。

public class TaskTest { private static final ExecutorService pool = Executors.newFixedThreadPool(5);// 线程池 public static final TaskTest me = new TaskTest(); public final int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; public static void main(String[] args) { me.start(); } private void start() { pool.execute(new Runnable() { @Override public void run() { while (true) { try { for (int i = 0; i < arr.length; i++) { if (1 == arr[i]) { System.out.println("start!"); Thread.sleep(1*1000L); } if (6 == arr[i]) { System.out.println("stop!"); Thread.sleep(5*1000L); } System.out.println(arr[i]); if (9 == arr[i]) { System.out.println("end!"); Thread.sleep(5*1000L); } } } catch (InterruptedException e) { e.printStackTrace(); } } } }); }}以上是"java中Timer定时器怎么用"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

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