java 定时器

本文介绍了JDK中两种定时任务的使用:javax.management.timer.Timer和java.util.Timer,以及更常用的java.util.concurrent.ScheduledExecutorService。通过实例展示了它们的工作原理和应用场景,强调ScheduledExecutorService的灵活性和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定时任务是我们在做项目的时候经常使用到的,比如定时发送心跳,定时请求数据等等。无论是使用开源的定时任务框架Quartz等,还是使用JDK原生态的定时任务都可以很好的完成这个任务。碰巧最近看源码看到了有的地方使用到了javax.management.timer.Timer,所以在这里记录下JDK中提供的几种定时任务的使用方法,权当做总结了~

1、javax.management.timer.Timer

对于这个类,有些人估计会感到陌生。在多数情况下将其和NotificationListener结合使用,可以捕获定时任务触发的事件作出相应的处理。

import java.util.Calendar;

import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.timer.Timer;


public class Timer1Test implements NotificationListener{

    private Timer t = new Timer();

    {        
        t.addNotificationListener(this, null, "");
        t.addNotification("a1", "a2", "a3", Calendar.getInstance().getTime(), 1000, 60);
        t.start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                int i = 0;
                while (i < 60) {
                    t.addNotification("a4", "a5", "a6", Calendar.getInstance().getTime());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    i++;
                }
            }
        }).start();
    }

    @Override
    public void handleNotification(Notification notification, Object handback) {
        System.out.println(notification.getSequenceNumber() + " " + notification.getTimeStamp() + " " + notification.getMessage());
    }

    public static void main(String[] args) {
        Timer1Test t = new Timer1Test();
    }
}

Timer可以触发一次性的事件,如上面启动的线程中Timer每隔一秒发送一个Notification,Listener捕获到后打印信息。同时Timer也可以定义周期性的Notification,而不用你自己启动线程去操作。
其原型如下,

public synchronized Integer addNotification(String type, String message, Object userData, Date date, long period, long nbOccurences)

这里主要解释下后两个参数,period表示定时任务执行的周期,而nbOccurences表示执行的次数。
运行上面的程序后可以发现有两种不同的消息每隔一秒钟在交叉的打印,执行60s的时候两个消息同时终止了。

2、java.util.Timer

这个可能大家比较熟悉了,就不做什么特别的解释了。简单的将用法写出来就好了,

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class Timer2Test {
    private Timer t = new Timer();
    {
        t.scheduleAtFixedRate(new TimerTask() {
            private int i = 0;
            @Override
            public void run() {
                System.out.println(i++);
            }
        }, Calendar.getInstance().getTime(), 1000);
    }

    public static void main(String[] args) {
        Timer2Test t = new Timer2Test();
    }
}

3、java.util.concurrent.ScheduledExecutorService

这个可能是大家现在最长使用到的了,利用线程池来完成定时任务。

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;


public class Timer3Test {
    private ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            // TODO Auto-generated method stub
            return new Thread(r);
        }
    });

    {
        es.scheduleWithFixedDelay((new Runnable() {
            private int i = 0;
            @Override
            public void run() {
                System.out.println(i++);
            }
        }), 0, 1000, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) {
        Timer3Test t = new Timer3Test();
    }
}

这种方法相比于前两种更加灵活,而且提供的功能也更加丰富。比如线程池的大小,线程池的大小决定这你所需要执行的这些定时任务能否准时的执行,如果线程大小为1,并且有好几个定时任务,并且他们触发的事件恰好相同的时候,如果某个任务执行时间很长就会影响其他任务,因为他们是在单线程中顺序执行的。灵活也就意味着使用要多加小心!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值