Three simple ways to implement timing tasks in Java

the first method:

    /**
     * 先定义一个任务每天执行的时间点,再写一个死循环,不断地拿当前时间和事先定义的时间去比对,若到时间则执行任务
     */
    @Test
    public void test1() {
        String taskTime = "13:43:10";
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        while (true) {
            Date date = new Date();
            if (sdf.format(date).equals(taskTime)) {
                System.out.println("任务开始执行!");
                try {
                    // 这里让线程睡眠一秒钟的原因是:若任务在1秒内执行完的话,会导致任务执行多遍,
                    // 任务执行完睡眠一秒钟,保证任务不会重复执行
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

The second method: If you want to test, please be sure to use the main method, Test will not work

    /**
     * 利用ScheduledExecutorService这个接口实现
     */
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                System.out.println("任务开始执行!");

            }
        };
        ScheduledExecutorService sch = Executors.newSingleThreadScheduledExecutor();
        // 第一个参数是要执行的线程
        // 第二个参数是初始延迟时间
        // 第三个参数是任务执行的间隔时间
        // 第四个参数是计时单位,可以是时分秒等
        sch.scheduleAtFixedRate(runnable, 10, 2, TimeUnit.SECONDS);
    }

The third method: If you want to test, please use the main method, Test will not work

public static void main(String[] args) {
        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                System.out.println("任务开始执行!");

            }
        };
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        cal.set(year, month, day, 14, 1, 0);
        Date date = cal.getTime();
        Timer timer = new Timer();
        timer.schedule(task, date, 2000);
    }

Guess you like

Origin blog.csdn.net/u011207400/article/details/130334190