如何用Cron编写ThreadPoolTask​​Scheduler?

时间:2019-03-05 07:17:42

标签: java multithreading scheduled-tasks

我正在尝试编写我的第一个taskExecutor,我对此有些疑问。

我需要同时执行3个任务。

我的配置正确吗?

配置应该与同一bean中的任务一起使用吗? (最佳做法)

@Configuration
@EnableScheduling
public class TaskExecutor {
    private static final Logger LOGGER = LogManager.getLogger(TaskExecutor.class);

    @Autowired
    private Processor processor;


    @Scheduled(cron = "0 55 23 28-31 * ?")
    public void firstTask() throws ParseException {

        }               
    }

    @Scheduled(cron = "0 55 23 28-31 * ?")
    public void secondTask() {

        }       
    }

    @Scheduled(cron = "0 55 23 28-31 * ?")
    public void thirdTask() {

        }
    }

    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        LOGGER.info("Setting up thread pool task scheduler with 3 threads.");
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(3);
        scheduler.setThreadNamePrefix("task-");
        scheduler.setAwaitTerminationSeconds(60);
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.setErrorHandler(t -> LOGGER.error(
                "Unknown error occurred while executing task.", t
        ));
        scheduler.setRejectedExecutionHandler(
                (r, e) -> LOGGER.error(
                        "Execution of task {} was rejected for unknown reasons.", r
                )
        );
        return scheduler;
    }
}

1 个答案:

答案 0 :(得分:0)

执行以下操作

@Scheduled(cron = "0 * * * * ?")
public void scheduleTaskWithCronExpression() {
    logger.info("Cron Task :: Execution Time - {}", dateTimeFormatter.format(LocalDateTime.now()));
}

或者,您可以 使用 CronTrigger 根据以下cron表达式安排任务:

CronTrigger cronTrigger   = new CronTrigger("10 * * * * ?");

提供的触发器可用于根据特定的指定节奏或时间表运行任务:

taskScheduler.schedule(new RunnableTask("Cron Trigger"), cronTrigger);

在这种情况下,RunnableTask将在每分钟的第10秒执行。