Java 多线程之定时器篇Timer
1. 定时器的作用
间隔特定的时间,执行特定的程序
比如:每个10秒钟备份一次程序
2. 定时器的实现
import java.text.*;
import java.util.*;
public class TimerTest {
public static void main(String[] args) throws ParseException {
//创建定时器
Timer timer = new Timer();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date firstTime = sdf.parse("2021-3-21 10:29:30");
//指定定时器任务:从firstTime开始,每隔5秒执行一次程序备份
timer.schedule(new MyTimerTask() ,firstTime, 1000 * 5);
}
}
class MyTimerTask extends TimerTask{
@Override
//编写要执行的任务
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-ddd HH:mm:ss");
System.out.println(sdf.format(new Date())+"文件保存一份");
}
}