Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

java - Creating Spring Framework task programmatically?

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...