JAVA定时任务

要求:
(保存上次执行时间)
一天一次
获取到的信息写到文件中
CrontabTask
StaticScheduleTask

询问清楚token是固定每天更换,还是说每次获取到的token时效时间为一天?

Timer方式

/**
 * 定时任务
 * 1.通过Timer实现
 * 2.@Scheduled实现
 */
public class CrontabTask {
    // 每秒获取上次执行的时间

    // 创建文件
    public static File createFile() throws IOException {
        File file = new File("src/main/resources/opservice.properties");
        if (!file.exists()) {
            file.createNewFile();
            System.out.println("opservice.properties被创建");
        }
        return file;
    }

    // 写内容到文件
    public static void writeContent2File(File file,String str) {
        try {
            FileWriter fw = new FileWriter(file);
            fw.write(str);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 安排指定的任务task在指定的时间firstTime开始进行重复的固定速率period执行
    public static void timer1(Date time) {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println("new timer1");
            }
        },time,1000*6);
    }

    // 昨天
    public static void getYesterday() {
        Long yesterday = new Date().getTime()-1000*60*60*24;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        System.out.println(sf.format(yesterday));
    }


    public static void main(String[] args) {
//        timer1(new Date());
//        try {
//            File file = createFile();
//            writeContent2File(file,"token=28394u55o5nccfnfmf,0909ui");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        getYesterday();

    }
}


@Scheduled 方式(springboot可用)

@Configuration //1.主要用于标记配置类,兼备Component的效果
@EnableScheduling // 2.开启定时任务,可以加在启动类上
public class StaticScheduleTask {
    //3.添加定时任务 5秒
    @Scheduled(cron = "0/5 * * * * ?")
    private void configureTasks() {
        System.out.println("执行定时任务:" + LocalDateTime.now());
    }
}

动态读取和写入resources内容参考
https://www.cnblogs.com/jmcui/p/10694360.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值