java定时运行程序,

直接看代码吧(run方法内的是运行的内容,start方法是启动。如果设置的时间是过去的时间,那么程序直接运行)

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimer extends TimerTask {

public static void start() {
DateFormat dfLong = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TestTimer apsut = new TestTimer ();
Timer timer = new Timer();
Date now = new Date();
Date dayStart = apsut.getTomDateStartTime(now);
System.out.println("===============等待第一次开始运行时间:" + dfLong.format(dayStart) + ",运行间隔为12个小时===============");
timer.schedule(apsut, dayStart, 1000 * 60 * 60 * 12);
}

public void run() {
Date now = new Date();
DateFormat dfLong = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("===============程序自动运行。时间:" + dfLong.format(now) + "===============");

System.out.println("===============程序运行停止,睡眠12小时。时间:" + dfLong.format(now) + "===============");
}

/*返回第二天的开始时间,秒数设置在59*/
private Date getTomDateStartTime(Date date) {
Timestamp timestamp = new Timestamp(date.getTime());
Calendar cal = Calendar.getInstance();
cal.setTime(timestamp);
cal.add(Calendar.DATE, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}

public static void main(String[] args) {
start();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值