【慕课笔记】Java定时任务调度工具详解之Timer篇_1实践

实践

【慕课笔记】Java定时任务调度工具详解之Timer篇_1实践_第1张图片
【慕课笔记】Java定时任务调度工具详解之Timer篇_1实践_第2张图片
【慕课笔记】Java定时任务调度工具详解之Timer篇_1实践_第3张图片
【慕课笔记】Java定时任务调度工具详解之Timer篇_1实践_第4张图片
【慕课笔记】Java定时任务调度工具详解之Timer篇_1实践_第5张图片
实践一下看看:
DancingRobot.java

package com.java.study.robot;

import java.text.SimpleDateFormat;
import java.util.TimerTask;

public class DancingRobot extends TimerTask {

    @Override
    public void run() {
        // 获取最近一次任务计划执行的时间,并将其格式化
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("schedule exec time is "
                + sf.format(scheduledExecutionTime()));
        System.out.println("DancingRobot is dancing...");
    }
}

WaterRobot.java

package com.java.study.robot;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

public class WaterRobot extends TimerTask {

    // 桶的最大容量假设为5L,初始化为0L
    private int bucketCapacity = 0;

    private Timer timer;
    // 构造器给timer赋值
    public WaterRobot(Timer timer) {
        this.timer = timer;
    }

    @Override
    public void run() {
        // 灌水直至桶满为止
        if (bucketCapacity < 5){
            System.out.println("WaterRobot is watering... 1L once.");
            bucketCapacity++;
        } else {
            // 水满就停止执行任务了
            System.out.println("the bucket is full!!!");
            System.out.println("the num of canceled tasks in timer is " + timer.purge());
            cancel();
            System.out.println("the num of canceled tasks in timer is " + timer.purge());
            // 灌水任务停止后,等待两秒, 然后停止所有任务即(DancingRobot任务也被停止)
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            timer.cancel(); //停止所有任务即(DancingRobot任务也被停止)
        }

    }
}

Executor.java

package com.java.study.robot;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;

public class Executor {
    public static void main(String[] args) {

        Timer timer = new Timer();

        // 获取当前时间
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("current time is " + sf.format(calendar.getTime()));

        DancingRobot dr = new DancingRobot();
        WaterRobot wr = new WaterRobot(timer);  // 水满之后停2秒,停止所有机器人任务,所以需要穿timer参数给WaterRobot

        timer.schedule(dr, calendar.getTime(), 2000);
        timer.scheduleAtFixedRate(wr, calendar.getTime(), 1000);
    }
}

执行效果:
【慕课笔记】Java定时任务调度工具详解之Timer篇_1实践_第6张图片

你可能感兴趣的:(定时任务,Timer)