java定時(shí)器

每天定時(shí)執(zhí)行(方法1)

public class DayInterval implements ServletContextListener{
public static void showDayTime() {
Date sendDate = new Date();
Timer dTimer = new Timer();
dTimer.schedule(new TimerTask() {
@Override
public void run() {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
if (hour == 11 && minutes == 38) {
// 每天執(zhí)行,若為11:38
System.out.println("每日任務(wù)已執(zhí)行");
}
}
}, sendDate, 24* 60* 60 * 1000);//設(shè)置24小時(shí)執(zhí)行一次
}

public static void main(String[] args) {
    showDayTime();
}

@Override
public void contextDestroyed(ServletContextEvent arg0) {
    // TODO Auto-generated method stub
    
}

@Override
public void contextInitialized(ServletContextEvent arg0) {
    showDayTime();
    
}

每天定時(shí)執(zhí)行(方法2)

public static void showDayTime() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);

    calendar.set(year, month, day, 10, 44, 00);//設(shè)置要執(zhí)行的日期時(shí)間

    Date defaultdate = calendar.getTime();

    Timer dTimer = new Timer();
    dTimer.schedule(new TimerTask() {
    @Override
    public void run() { 
         System.out.println("每日任務(wù)已經(jīng)執(zhí)行");
    }
    }, defaultdate , 24* 60* 60 * 1000);//24* 60* 60 * 1000
}

public static void main(String[] args) {
    showDayTime();
}

每月定時(shí)執(zhí)行

public static void showMonthTime() {
Date sendDate = new Date();

    Timer dTimer = new Timer();
    dTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            if (day == 30) {
                // 每天執(zhí)行,若為每月30號(hào)才執(zhí)行
                System.out.println("每月定時(shí)任務(wù)已執(zhí)行");
            }
        }
    }, sendDate,  24* 60* 60 * 1000);//24* 60* 60 * 1000
}

public static void main(String[] args) {
    showMonthTime();

}

轉(zhuǎn)載 https://blog.csdn.net/z_victoria123/article/details/82908428

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容