手写 java定时器功能实例

java工具类中可以使用定时器功能。假设我们要设置一个周期定时任务,或者日期定时任务可以使用

Timer timer = new Timer();
timer.scheduleAtFixedRate(task, delay, period);

task是业务逻辑,只要根据自己的需求写需要干什么就可以了,delay是第一次执行定时器的时机,period是循环执行定时器的时机,单位都是毫秒。

这个最复杂的就是你第一次执行的时间是多少了,所以需要自己写一些方法去实现。下面我的思路捋一下,就是在数据库中或者配置文件中保存类似“4  08:16:10”这样子的信息,

4代表星期 后面就代表执行的具体时间了,然后去获取,截取星期和具体时间,计算第一次的执行时机。

代码如下:
/***
 * @author ZHanG
 *这个类主要就是将设置周期定时器的第一个时间的毫秒值的计算
 *        Timer timer = new Timer();
        timer.scheduleAtFixedRate(task, delay, period);
        设置的参数为delay
 */
public class WeekMsec {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        //输入星期,可以从数据库获取
        int weekDay = 4;
        //设置星期得加1
        calendar.set(Calendar.DAY_OF_WEEK, weekDay+1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = dateFormat.format(calendar.getTime());
        //可以从数据库获取time
        String time = "08:16:10";
        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_WEEK, 7);
            }
        } catch (Exception e) {
        }
        long delay = calendar.getTimeInMillis()-current.getTimeInMillis();
        //获取的毫秒值
        System.out.println(delay);
    }
    
}

下面是日期定时器,逻辑基本跟上面无异:
/***
 * @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);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36026747/article/details/80884397