7

I need to create task on the fly in my app. How can I do that? I can get scheduler with @autowired annotation, but scheduler takes Runnable objects. I need to give Spring objects, so that my tasks can use @autowired annotation too.

@Autowired private TaskScheduler taskScheduler;
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
newbie
  • 24,286
  • 80
  • 201
  • 301

1 Answers1

16

You just need to wrap your target object in a Runnable, and submit that:

private Target target;  // this is a Spring bean of some kind
@Autowired private TaskScheduler taskScheduler;

public void scheduleSomething() {
    Runnable task = new Runnable() {
       public void run() {
          target.doTheWork();
       }
    };
    taskScheduler.scheduleWithFixedDelay(task, delay);
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • I cannot access target in that context. Eclipse says sytnax error. – newbie Dec 21 '10 at 12:38
  • 1
    @newbie: Yes, I was giving you the general idea, not working code. – skaffman Dec 21 '10 at 12:41
  • problem sovled, I added implements Runnable to my task class (aka target) – newbie Dec 21 '10 at 12:52
  • 2
    @skaffman For some reason, the taskScheduler is not injected. Do you know if a TaskScheduler is created when EnableScheduling is set on the configuration class? Thanks! – manash Dec 23 '15 at 12:02