zhangboyu
zhangboyu

Reputation: 243

In java how to pass parameter to a method with @scheduled?

Now I have a scheduled method:

@Scheduled(corn = "0 0 0 * * *")
public void method(){
  // do something;
}

Now I wish to pass a parameter (boolean save) to the method. Here save =true while the method is called scheduled, and save = false while the method is called in another way, which is like:

@Scheduled(corn = "0 0 0 * * *")
public void method(boolean save){
  // do something;
}

But it returns an error:

Only no-arg methods may be annotated with @Scheduled

So How can I achieve this?

Upvotes: 1

Views: 4416

Answers (2)

T A
T A

Reputation: 1756

Now I wish to pass a parameter (boolean save) to method. Here save = true while the method is called scheduled, and save = false while the method is called in other way

You can't use parameters in a sheduled method. What you could do is overload your method like this:

@Scheduled(corn = "0 0 0 * * *")
public void method(){
  // do something;
}

public void method(boolean save){
  if (save) {
     method();
     return;
  }
  // do something else;
}

This way when you call method(false), your second method will be called, if you call method(true) your first method will be executed inside of your second method while still making your first method available for sheduling.

Upvotes: 2

Kenyore
Kenyore

Reputation: 56

You can get both scheduled and manual call way of tasks by using Elastic-job.It provides a triger api to call task manual.

If you need this save flag to do someting different,I think you should pull away logic here and provide it for different entrance. Like this

public void doSomething(boolean flag) {
  // do something;
}

@Scheduled(corn = "0 0 0 * * *")
public void method(){
  doSomething(true);
}

@RequestMapping("/xxx")
public void method(){
  doSomething(false);
}

Upvotes: 1

Related Questions