java 定时执行任务

1.使用java并发库编写定时程序。 如定时上传文件,定时删除日志,定时执行sql 等

下面的程序在每天的23:20:30 后,执行一次具体任务
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MyTimer implements Runnable{
 //执行标志位 true:可以执行,false:不可以执行
 private boolean flag = true;
 
 public int getCurrTime(){
  Calendar cal = Calendar.getInstance();
  SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
  return Integer.valueOf(sdf.format(cal.getTime()));
 }
 
 @Override
 public void run() {
  //转天状态改变
  if((getCurrTime() < 1)&&(!flag)){
   System.out.println("======"+getCurrTime());
   flag = true;
  }
  //ball 模式
  if(getCurrTime() < 232030){
   System.out.println("return!!!");
   return ;
  }
  
  if(flag){
   //执行具体任务
   Calendar cal = Calendar.getInstance();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   System.out.println("cur date::"+sdf.format(cal.getTime()));
   flag = false;

  }else{
   System.out.println("==============false-------------");
  }
 }

 public static void main(String args[]) {

  try {
   ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
   exec.scheduleAtFixedRate(new MyTimer(), 1, 2, TimeUnit.SECONDS);
  } catch (RejectedExecutionException e) {
   e.printStackTrace();
  }
  
  
  
 }

}

猜你喜欢

转载自gjp014.iteye.com/blog/2008409