java定时器

每天定时执行(方法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) {
// 每天执行,若为11:38
System.out.println("每日任务已执行");
}
}
}, sendDate, 24* 60* 60 * 1000);//设置24小时执行一次
}

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();
    
}

每天定时执行(方法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);//设置要执行的日期时间

    Date defaultdate = calendar.getTime();

    Timer dTimer = new Timer();
    dTimer.schedule(new TimerTask() {
    @Override
    public void run() { 
         System.out.println("每日任务已经执行");
    }
    }, defaultdate , 24* 60* 60 * 1000);//24* 60* 60 * 1000
}

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

每月定时执行

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) {
                // 每天执行,若为每月30号才执行
                System.out.println("每月定时任务已执行");
            }
        }
    }, sendDate,  24* 60* 60 * 1000);//24* 60* 60 * 1000
}

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

}

转载 https://blog.csdn.net/z_victoria123/article/details/82908428

你可能感兴趣的:(java定时器)