Java定时任务,每天凌晨1点执行

发布时间:2020-03-28 17:29:29 作者:Mos 阅读量:10374

调用方法:

import timer.MyTimerTask;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

public class Main {

    private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        /*** 定制每日23点50分执行方法 ***/
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 50);
        calendar.set(Calendar.SECOND, 0);
        Date sendDate = calendar.getTime();
        if (sendDate.before(new Date())) {
            sendDate = addDay(sendDate, 1);
        }
        Timer timer = new Timer();
        timer.schedule(new MyTimerTask(), sendDate, PERIOD_DAY);
    }

    // 增加或减少天数
    public static Date addDay(Date date, int num) {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, num);
        return startDT.getTime();
    }
}


执行器MyTimerTask.java


package timer;

import deal.BlogDeal;
import deal.MovieDeal;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

    private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void run() {
        System.out.println(formatter.format(Calendar.getInstance().getTime()) + ":当天定时任务开始");
        BlogDeal.insertToday(MovieDeal.getToday());
        System.out.println(formatter.format(Calendar.getInstance().getTime()) + ":当天定时任务结束");
    }
}


转载请注明出处:文思齐远博客,如果对您有帮助,请帮忙点一下右侧的广告,谢谢您了!
支付宝打赏 微信打赏

我要评论

猜你想搜

实时天气

©2020 i847.cn
部分内容转自网络,如有损害您的权益,致邮联系:jiang2008wen#126.com,一经证实,立即删除!    我要留言
备案号:蜀ICP备18020563号-1