定时任务2

1、场景分析

  微信、QQ定时推送步数;网易云音乐定时推送歌单;手机定时闹钟;定时发送邮件;淘宝购物15分钟内付款、10天内自动收货;支付宝蚂蚁森林定时长成;支付宝、京东定时推送账单、信用。

2、使用技术

2.1 Timer定时器

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by lq on 2018/10/8.
 */
public class MyTimer {
    public static void main(String[] args) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                LocalDateTime current = LocalDateTime.now();
                String timeString = current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                System.out.println("task  run:"+ timeString);
            }
        };
        Timer timer = new Timer();
        //定时任务3秒后启动,每1秒执行一次
        timer.schedule(timerTask,3000,1000);
    }
}

2.2 ScheduledExecutorService

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceDemo {
    public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        LocalDateTime current = LocalDateTime.now();
        // 参数:1、任务体 2、首次执行的延时时间
        //      3、任务执行间隔 4、间隔时间单位
        service.scheduleAtFixedRate(()->System.out.println("task ScheduledExecutorService "+current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))), 3, 1, TimeUnit.SECONDS);
    }
}

2.3 spring boot quartz

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