Question: How can I run a task from the command line for long-running jobs like reports from Jenkins in Spring Boot? I'm looking for something similar to Ruby on Rails Rake tasks. Rake tasks execute the code from the command line in the same application context as the web server so that you can re-use code. 

* I found [Spring Batch](https://spring.io/projects/spring-batch#overview) but it sounded more like [Resque](https://github.com/resque/resque).
* I found [command line runners](https://therealdanvega.com/blog/2017/04/07/spring-boot-command-line-runner) but it said that they all run before the web server starts, so I can't *not* run it or only run one task.
* I found [scheduled tasks](https://spring.io/guides/gs/scheduling-tasks/) which sounds *perfect*, but my app is load balanced with many instances so I would not want it running multiple times at once!

I have a report where the query takes more than 30s to run, and generates a CSV file I would like to mail. I want it to run automatically each week with cron or Jenkins.

Answer: 
I hacked a solution. Suggestions welcome.

```
package com.example.tasks;

@Component
public class WeeklyReport implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        Arrays.asList(args).stream().forEach(a -> System.out.println(a));
        if (!(args.length > 0 && args[0].equals("-task report:weekly"))) return;
        System.out.println("weekly report");
        System.exit(0);
    }

```

And running it from a 'cron' job with

```
$ mvn spring-boot:run -Drun.arguments="-task report:weekly"

```

<https://docs.spring.io/spring-boot/docs/1.5.19.RELEASE/reference/htmlsingle/#boot-features-command-line-runner>

<https://www.baeldung.com/spring-boot-command-line-arguments>

<https://therealdanvega.com/blog/2017/04/07/spring-boot-command-line-runner>
I was facing a similar problem recently and I came up with these three possible solutions:

1. Designate a "housekeeper" role that can be assumed by at most one instance whose responsibility would be complete the scheduled job. But for this the housekeeper would have to send a heartbeat to the others (through the load balancer..) and if it stops then the remaining instances must elect a new one so it seems to be an interesting but way more complex approach that I might play with later.
2. Have a single-instance external service that would run scheduled tasks and will generate the weekly csv for you
3. Have a single-instance external service that only has the capacity to make scheduled api calls and that would call your original service through the load balancer. I prefer this solution as all the resources to complete the task are already present at the original service and it preserves the functionality. It is also flexible as the scheduler service can be replaced by more light weight cron job with a curl call or merged to another service in the future..etc.