首页 > 解决方案 > 安排 Cronjob 更改运行时 - JAVA

问题描述

我需要传递值运行时间,并且根据值我需要更改 cronjob 执行间隔,但是当我使用 @Scheduled() 时我不能这样做,因为它需要常量。我该怎么做或是否有其他方法?我也无法将 env.getProperty 值分配给本地方法之外的变量。

  String cronValue=env.getProperty("cron");


    @Override
    @Scheduled(cron = "0 0 0 * * *", zone = "Asia/Colombo")
    public void createFile() throws IOException {

        String location=env.getProperty("location");

        LocalDate today = LocalDate.now( ZoneId.of( "Asia/Colombo" ) );
        String date = today.toString();
        String source=location+"report-temp.csv";
        String dailyFile=location+"report-"+date+".csv";



        // File (or directory) with old name
        File oldFile = new File("/home/lkr/nish/report-temp.csv");


        File newFile = new File(dailyFile);
        //if(file2.exists()) throw new java.io.IOException("file exists");


        boolean success = oldFile.renameTo(newFile);
        if (!success) {
            // File was not successfully renamed
        }


        System.out.println("Daily File Created!");
    }

标签: javaspringspring-boot

解决方案


嗯,您可以尝试使用TaskScheduler Spring 接口。

基本上,它允许您调用调度方法并传递RunnableDate参数。

在这种情况下,您的调用需要实现 Runnable 并以日期格式参数化您的动态执行周期。假设您有一个名为 FileGenerator 的类,并且它实现了 Runnable。它还必须实现 Runnable 接口的方法,因此您必须有一个名为 run(); 的方法;

class FileGenerator implements Runnable {
    TaskScheduler scheduler;
    Date parametrizedDate;

    @Override
    public void run() {
        scheduler.schedule(this::createFile, parametrizedDate);
    }


    private void createFile() {

        String location=env.getProperty("location");

        LocalDate today = LocalDate.now( ZoneId.of( "Asia/Colombo" ) );
        String date = today.toString();
        String source=location+"report-temp.csv";
        String dailyFile=location+"report-"+date+".csv";

        // File (or directory) with old name
        File oldFile = new File("/home/lkr/nish/report-temp.csv");

        File newFile = new File(dailyFile);
        //if(file2.exists()) throw new java.io.IOException("file exists");

        boolean success = oldFile.renameTo(newFile);
        if (!success) {
            // File was not successfully renamed
        }

        System.out.println("Daily File Created!");
    }

由于 TaskScheduler 本身就是一个接口,因此您必须配置它的一个实现,最好是在一个 bean 中。使用 ThreadPoolTask​​Scheduler 的一种可能性:

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
    ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(5);
        threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
        return threadPoolTaskScheduler;
    }

剩下要做的就是用字段自动装配 bean 并提供您想要传递的日期。

编辑:此界面还为您提供了可以传递时间跨度(固定或延迟)的方法。更多关于它的信息在这里


推荐阅读