每天定時(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