定时器功能实例
java工具类中可以使用定时器功能。假设我们要设置一个周期定时任务,或者日期定时任务可以使用
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, delay, period);
task是业务逻辑,只要根据自己的需求写需要干什么就可以了,delay是第一次执行定时器的时机,period是循环执行定时器的时机,单位都是毫秒。
这个最复杂的就是你第一次执行的时间是多少了,所以需要自己写一些方法去实现。下面我的思路捋一下,就是在数据库中或者配置文件中保存类似“4 08:16:10”这样子的信息,
4代表星期 后面就代表执行的具体时间了,然后去获取,截取星期和具体时间,计算第一次的执行时机。
代码如下:
1 /*** 2 * @author ZHanG 3 *这个类主要就是将设置周期定时器的第一个时间的毫秒值的计算 4 * Timer timer = new Timer(); 5 timer.scheduleAtFixedRate(task, delay, period); 6 设置的参数为delay 7 */ 8 public class WeekMsec { 9 public static void main(String[] args) { 10 Calendar calendar = Calendar.getInstance(); 11 //输入星期,可以从数据库获取 12 int weekDay = 4; 13 //设置星期得加1 14 calendar.set(Calendar.DAY_OF_WEEK, weekDay+1); 15 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 16 String dateStr = dateFormat.format(calendar.getTime()); 17 //可以从数据库获取time 18 String time = "08:16:10"; 19 String str = dateStr+" "+time; 20 System.out.println(str); 21 Calendar current = Calendar.getInstance(); 22 try { 23 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 24 Date date =format.parse(str); 25 calendar.setTime(date); 26 //判断是否在今日之前 27 if(calendar.before(current)){ 28 calendar.add(Calendar.DAY_OF_WEEK, 7); 29 } 30 } catch (Exception e) { 31 } 32 long delay = calendar.getTimeInMillis()-current.getTimeInMillis(); 33 //获取的毫秒值 34 System.out.println(delay); 35 } 36 37 }
下面是日期定时器,逻辑基本跟上面无异:
/*** * @author ZHanG *这个类主要就是将设置日期定时器的第一个时间的毫秒值的计算 * Timer timer = new Timer(); timer.scheduleAtFixedRate(task, delay, period); 设置的参数为delay */ public class DayMsec { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String dateStr = dateFormat.format(calendar.getTime()); String time = "23:06:00"; String str =dateStr+" "+time; System.out.println(str); Calendar current = Calendar.getInstance(); try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = format.parse(str); calendar.setTime(date); if(calendar.before(current)){ calendar.add(Calendar.DAY_OF_YEAR, 1); } } catch (Exception e) { } long delay = calendar.getTimeInMillis()-current.getTimeInMillis(); System.out.println(delay); } }

浙公网安备 33010602011771号