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);

    }
}
经验分享 程序员 微信小程序 职场和发展