JAVA中的定时器(Timer)

JAVA中的定时器(Timer)

  • 定时器的作用:
    间隔特定的时间,执行特定的程序

  • 在实际开发中,每隔多久执行一段特定的程序,这种需求是很常见的,
    那么在java中可以采用多种方式实现:
    1、可以使用sleep方法,睡眠,设置睡眠时间,每到这个时间醒来,执行任务
    这种方式是最原始的定时器(比较low)
    2、在java的类库中已经写好了一个定时器:java.util.Timer,可以直接
    拿来用,不过这种方式在目前的开发中也很少用,因为现在有很多高级框架
    都是支持定时任务的
    3、在实际开发中,目前使用较多的是Spring框架中提供的SpringTask框架,
    这个框架只要进行简单的配置,就可以完成定时器的任务。

public class Timer01 {
    public static void main(String[] args) throws ParseException {
        //设置第一次运行时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date firstTime = sdf.parse("2020-7-10 13:31:30");

        //创建定时器对象
        Timer timer = new Timer();
//        Timer timer = new Timer(true);  //设为守护线程模式

        //指定定时任务
        timer.schedule(new LogTimerTask(),firstTime,1000 * 10);

    }
}
//编写一个定时类,即定时任务
class LogTimerTask extends TimerTask {
    @Override
    public void run() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(new Date()) + "——>备份成功");
    }
}

使用匿名内部类的方式创建定时任务:

public class Timer02 {
    public static void main(String[] args) throws ParseException {
        //设置第一次运行时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date firstTime = sdf.parse("2020-7-10 13:31:30");

        //创建定时器对象
        Timer timer = new Timer();
//        Timer timer = new Timer(true);  //设为守护线程模式

        //指定定时任务
        timer.schedule(new TimerTask() {
            //编写一个匿名内部类,即定时任务
            @Override
            public void run() {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println(sdf.format(new Date()) + "——>备份成功");
            }
        }, firstTime, 1000 * 10);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值