We often get a requirement of scheduling a task or monitoring some event consistently when our application is running on server.
In that case we need to create a thread in our application that will constantly monitor the event in our application and start the task after every fixed interval of time.
In Mule we get plenty of options of doing it like using Quartz scheduler or Poll component etc.
But what if we want to use our custom java class for that ???
Yes, we can do a scheduling and monitoring activity using a Java class and Spring task scheduler in our Mule application….
Let’s consider we have a simple Mule flow as following:-
Now, this is a simple flow where we will hit a url in the browser and it will send a response to the browser and log the payload in console.
Now, we will also create a Java class here that will constantly load itself after the application run in the server after every 10 sec and will print a message in console.
Let’s consider we our Java class is as following:-
This is a simple Java class that will log a message after every 10 seconds and will be running in our application and will be monitoring in our application.
We can customize this class as per our requirement and put our own code here for monitoring.
So far, I have kept it simple only to demonstrate the functionality.
So here is our Spring configuration in the Mule config that will trigger this class after every 10 second and keep the thread alive for monitoring and printing in the console:-
Here you can see the Spring task scheduler is scheduling the Java class after every 10 sec. Also there is a Mule flow that will print the message in the browser and console if we hit the url http://localhost:8082/test in browser
Testing our application
So if we run our application we will see the message after every 10 sec.:-
So if we hit url http://localhost:8082/test in browser we will get the following .:-
Also in the console we will get .:-
But the interesting fact is that Spring task scheduler is executing the Java class after every 10 sec.
So, using Java and Spring you can schedule and monitor events in Mule which you can use as an alternative to Quartz and Poll components.
So, you can try this example by your own and modify it as per your requirement.