java 定时开始执行程序

package com.zx.ps.web.gzdb;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ckx {
    //初始化计数
    static int count = 0;
    
    public static void showTimer() {
        final Timer timer = new Timer();
        //创建定时器任务
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                ++count;
                System.out.println("时间=" + new Date() + " 执行了" + count + "次"); // 1次
                switch (count) {
                case 3:
                    timer.cancel();
                    System.out.println("规定时间运行三次结束定时任务!");
                    break;
                }
            }
        };
        
        //设置执行时间
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
        //定制每天的11:40:00执行,
        calendar.set(year, month, day, 11, 58, 00);
        Date date = calendar.getTime();
        
        int period = 30 * 1000;
        //每天的date时刻执行task,每隔30秒重复执行
        timer.schedule(task, date, period);
        //每天的date时刻执行task, 仅执行一次
        //timer.schedule(task, date);
    }

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

 

posted on 2017-08-29 12:01  ckx0709  阅读(508)  评论(0编辑  收藏  举报

导航