java中的定时加载任务

1.将要执行任务的主类:

public class Test  {

public static void show(){
 try {
  Thread.sleep(10000);
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 StringBuffer sb=new StringBuffer();
 sb.append("234");
 System.out.println(sb.toString());
 sb.setLength(0);
 System.out.println(">>"+sb.toString());
 System.out.println(System.currentTimeMillis());
}

}

2.方法一:通过TimeTask调用:

public class App
{
    public static void main( String[] args )
    {
     getInfo();

    }
    public static  void getInfo(){
     TimerTask task = new TimerTask() {
            @Override
            public void run() {
             try {
        Test.show();
        System.out.println("!!!!!!!!!over!!!!!!!!!");
        //System.exit(0);
       } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
            }
        };
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
        //定制每天的21:09:00执行,
        calendar.set(year, month, day, 18, 12, 00);
        Date date = calendar.getTime();
        Timer timer = new Timer();
        System.out.println(date);
       
        int period = 2* 1000;//设置定时的间隔
        //每天的date时刻执行task,每隔2秒重复执行
        timer.schedule(task, date, period);
        //每天的date时刻执行task, 仅执行一次
        //timer.schedule(task, date);
        System.out.println(System.currentTimeMillis());
    }
   
   
}

3.通过 ScheduledExecutorService定时调用:

public class App
{
    public static void main( String[] args )
    {
     //getInfo();
Runnable runable = new Runnable(){
   
   public void run(){
    
    Test.show();
    System.out.println("!!!!!!!!!over!!!!!!!!!");
    
   }
   
  };
 ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
  
  service.scheduleAtFixedRate(runable, 0, 6, TimeUnit.SECONDS);
    }
}

你可能感兴趣的:(java)