传统定时器Timer

关键语法:new Timer().schedule(TimerTask task, long delay)

1.设置一个定时器,两秒执行一次

 new Timer().schedule(new TimerTask() {
       @Override
       public void run() {
           System.out.println("bombing!");
       }
   }, 2000);

2.如何每隔2s、4s交替执行

  1. 定义两个定时器,执行时间分别为2秒和4秒,两个定时器相互调用,即可实现
/**
  * 2秒执行的定时器
  */
static class MyTimer2 extends TimerTask {
    static int count = 0;

    @Override
    public void run() {
        count = (count + 1) % 2;
        System.out.println("second bombing!");
        new Timer().schedule(new MyTimer4(), 2000);
    }
}
/**
 * 4秒执行的定时器
 */
static class MyTimer4 extends TimerTask {
    static int count = 0;

    @Override
    public void run() {
        count = (count + 1) % 2;
        System.out.println("second bombing!");
        new Timer().schedule(new MyTimer2(), 4000);
    }
}
public static void main(String[] args) {
        new Timer().schedule(new MyTimer4(), 2000);

        while (true) {
            System.out.println(new Date().getSeconds());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

这里写图片描述
2. 2s和4s间歇性执行有一个特点,基数执行2s的,偶数执行4s的,可以利用静态变量实现此功能

static class MyTimer extends TimerTask {
        //静态变量:统计该执行那个定时器,基数:2s 偶数:4
        static int count = 0;
        @Override
        public void run() {
            count = (count + 1) % 2;//获得基偶数
            System.out.println("second bombing!");
            new Timer().schedule(new MyTimer(), 2000+2000*count);//2s,4s交替时间
        }
    }

 public static void main(String[] args) {
        new Timer().schedule(new MyTimer(), 2000);

        while (true) {
            System.out.println(new Date().getSeconds());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
执行结果与方法1一致

//quartz 目前spring中常用的定时器,可以指定到年月日,时分秒的执行,有兴趣的可以去看一下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值