java定时任务
1.按指定频率间隔执行某个任务。
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Aaaaa {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
// task to run goes here
System.out.println("Hello !!");
}
};
ScheduledExecutorService service = Executors
.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 10, TimeUnit.SECONDS);
}
}
2.周期定时执行某个任务。
- /**
- * 获取指定时间对应的毫秒数
- * @param time "HH:mm:ss"
- * @return
- */
- private static long getTimeMillis(String time) {
- try {
- DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
- DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
- Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
- return curDate.getTime();
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return 0;
- }
- /**
- * 每天晚上8点执行一次
- * 每天定时安排任务进行执行
- */
- public static void executeEightAtNightPerDay() {
- ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
- long oneDay = 24 * 60 * 60 * 1000;
- long initDelay = getTimeMillis("20:00:00") - System.currentTimeMillis();
- initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
- executor.scheduleAtFixedRate(
- new EchoServer(),
- initDelay,
- oneDay,
- TimeUnit.MILLISECONDS);
- }
- class EchoServer implements Runnable {
- @Override
- public void run() {
- try {
- Thread.sleep(50);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("This is a echo server. The current time is " +
- System.currentTimeMillis() + ".");
- }
- }

浙公网安备 33010602011771号