I have created spring boot application with spring cloud task which should executes a few commands(tasks). Each task/command is shorted-lived task, and all tasks are start
Similar to this answer https://stackoverflow.com/a/44482525/986160 but using injection and less configuration.
Having a similar requirement, what has worked for me is to have one CommandLineApps
class implementing CommandLineRunner
, then inject all my other command line runners as @Component
and use the first argument to delegate to one of the injected runners. Please note that the injected ones should not extend CommandLineRunner
and not be annotated as @SpringBootAppplication
.
Important: be careful though if you put the call in a crontab one call will destroy the previous one if it is not done.
Here is an example:
@SpringBootApplication
public class CommandLineApps implements CommandLineRunner {
@Autowired
private FetchSmsStatusCmd fetchSmsStatusCmd;
@Autowired
private OffersFolderSyncCmd offersFolderSyncCmd;
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(CommandLineApps.class, args);
ctx.close();
}
@Override
public void run(String... args) {
if (args.length == 0) {
return;
}
List restOfArgs = Arrays.asList(args).subList(1, args.length);
switch (args[0]) {
case "fetch-sms-status":
fetchSmsStatusCmd.run(restOfArgs.toArray(new String[restOfArgs.size()]));
break;
case "offers-folder-sync":
offersFolderSyncCmd.run(restOfArgs.toArray(new String[restOfArgs.size()]));
break;
}
}
}
@Component
public class FetchSmsStatusCmd {
[...] @Autowired dependencies
public void run(String[] args) {
if (args.length != 1) {
logger.error("Wrong number of arguments");
return;
}
[...]
}
}