本文介绍了如何在Java代码中安排任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在春季上下文中安排任务

I know how to schedule task in spring context:

  <task:scheduler id="taskScheduler" pool-size="1" />
  <task:scheduled-tasks scheduler="taskScheduler">
    <task:scheduled ref="jobWatcher" method="run" cron="*/10 * * * * ?" />
  </task:scheduled-tasks>

但是我的任务计划可以在运行时配置,所以我需要用Java代码创建任务.在春季文档中: http://docs.spring.io/spring/docs/3.0.x/reference/scheduling.html 是这样的:

But cron of my task can by configured during runtime so I need to create task in java code. In spring docs: http://docs.spring.io/spring/docs/3.0.x/reference/scheduling.html is something like this:

scheduler.schedule(task, new CronTrigger("* 15 9-17 * * MON-FRI"));

这是我想要的,但是我不知道他们在此示例中如何创建调度程序以及他的班级是什么.请帮助

which is what I want but I have no idea how their create scheduler in this example and what is his class. Please help

推荐答案

与XML配置或批注配置(您可以在其中直接指定Spring托管bean的方法)不同,您需要创建自己的Runnable,以调用您的方法.

Unlike XML configuration or annotation configuration (where you can specify directly a method of a Spring managed bean), you need to create your own Runnable which will call your method.

假设您有以下托管bean:

Say you have the following managed bean:

@Component
public class SchedulingBean{
    public void doSomethingPeriodically(){
    }
}

并且您想在动态cron上运行该方法,您有(至少)三个选项:

and you want to run the method inside on a dynamic cron, you have (at least) three options:

SchedulingBean实现Runnable并从run方法调用doSomehtingPeriodically方法

Let SchedulingBean implement Runnable and call the doSomehtingPeriodically method from the run method

@Component
public class SchedulingBean implements Runnable{
    public void doSomethingPeriodically(){
}
@Override
public void run(){
    doSomethingPeriodically();
    }
}

创建一个新的(可能是匿名的)Runnable实例,该实例从托管Bean内调用该方法.这可能有点棘手,因为您将需要从Spring上下文中获取对该bean的引用.

Create a new (maybe anonymous) Runnable instance that calls the method from within the managed bean. This could be a little trickier, as you will need to get the reference to that bean from the Spring context.

或创建一个新的(可能是匿名的)Runnable实例,该实例直接实现所需的功能,而无需使用托管bean:

Or create a new (maybe anonymous) Runnable instance that implements directly the needed functionality, without using a managed bean:

public class SchedulingBean implements Runnable{
    public void doSomethingPeriodically(){
    }
    @Override
    public void run(){
        doSomethingPeriodically();
    }
}

(请注意缺少的@Component)

这篇关于如何在Java代码中安排任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 04:44