Issue
I am trying to run a cronjob every 5 mins, the actual task is to trigger a curl end point from within the java class in a method. my crontab -e looks like below: */5 * * * * bash /home/ec2-user/script.sh the above line is working fine but it is not triggering the FTPConnect.start() from the Cron job class my Cron job looks like below: @Component public class CJob{
@Scheduled(cron="*/5 * * * * curl -v http://localhost:8080/apiname/v1/cids/$filename" ) // Every 12 hours
public static void fetchFromSFTP() {
try {
FTPConnect.start();
return;
} catch (Exception e) {
System.out.println("There was an error running this cron.");
e.printStackTrace();
System.exit(1);
}
}
}
Solution
Wow the way you ask the question and the information you give is pretty confusing - anyways I'm trying to answer.
First of all - as I understood - you have a real cronjob
activated on a unix machine, which is executing a task/ script periodically (every 5 min).
From your cron (or from within your script - it doesn't matter) you can call a java application with the java -jar ${yourJarName}
command.
For this to work, you of course need to install and setup Java
properly (install the JRE and maybe set some environment variables like JAVA_HOME
).
When this is the case Java will be able to start successfully. To make it to start and run your application/ JAR
successfully, your program needs to contain a valid main method. It' signature is public static void main(args[])
. Without such a method Java will not be able to run any application.
Within the main method you can do anything you like - e.g. call your fetchFromSFTP
method to perform the task.
In the above scenario the scheduling will be controlled by the unix system cron scheduler.
As you've used the @Scheduled
annotation it might be the case you've created a WAR
file and are executing it in a Servlet Container/ Application Container like Tomcat, Wildfly or Websphere Liberty.
This is also possible, but in this case you don't need to setup and use the unix systems cron scheduler. Since your WAR
file will be executed in an Application Container which is running 24/7 by itself and the Application Containers cron scheduler will be used to execute your fetchFromSFTP
method periodically.
I hope this is helpful and clears it up to you.
Answered By - Sebsen36 Answer Checked By - Mary Flores (WPSolving Volunteer)