i am not really familiar with Spring's Live Reload feature. However, i noticed that every time i have changes saved on my Java code. Java profiles (JMC) or Eclipse's (Debug Mode) shows that the thread i already spawned was spawned again resulting on 2 threads (1 thread before reload + 1 thread after reload).
I am currently using ThreadPoolExecutor to spawned my threads. basically i am letting spring manage my threads. In this case, How to i force shutdown/interrupt the threads i spawned when there is live reload occuring?
Below is my source.
ApplicationThreadingConfiguration.java
#Configuration
public class ApplicationThreadingConfiguration {
private static final Logger logger = LoggerFactory.getLogger(ApplicationThreadingConfiguration.class);
#Autowired
MyProperties prop;
#Bean(name = "myThread")
public TaskExecutor taskExecutor() {
logger.info(prop.toString());
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(prop.getCorePoolSize());
executor.setMaxPoolSize(prop.getMaxPoolSize());
executor.setQueueCapacity(prop.getQueueCapacity());
executor.setThreadNamePrefix("MyThread-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
return executor;
}
}
AppEventConfiguration.java (this spawns my thread after Spring context is loaded)
#Configuration
public class AppEventConfiguration {
private static final Logger logger = LoggerFactory.getLogger(AppEventConfiguration.class);
#Autowired
private MyService service;
#Autowired
private ApplicationContext context;
#Autowired
#Qualifier("myThread")
private TaskExecutor executor;
#EventListener(ApplicationReadyEvent.class)
public void onApplicationReadyEvent() {
service.getSomethingFromDB().stream().forEach(dto -> {
logger.info("Id: {}", dto.getId());
MyRunnableThread t = this.context.getBean(MyRunnableThread.class);
t.setMyId(dto.getId());
executor.execute(t);
});
}
}
MyRunnableThread.java
#Component
#Scope("prototype")
public class MyRunnableThread implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(MyRunnableThread.class);
private long myId;
#Override
public void run() {
while(true) {
try {
logger.info("Do something here on ID: {}",this.myId);
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void setMyId(long id) {
this.myId = myId;
}
}
myproperties.properties
myprop.core-pool-size=80
myprop.max-pool-size=100
myprop.queue-capacity=100
I have created a simple service like ... where I have to take some data from database at later
package com.spring.scheduler.example.springscheduler;
import org.springframework.stereotype.Service;
#Service
public class ExampleService {
private String serviceName;
private String repository;
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getRepository() {
return repository;
}
public void setRepository(String repository) {
this.repository = repository;
}
}
Here is my task scheduler created to run different threads.
#Component
public class TaskSchedulerService {
#Autowired
ThreadPoolTaskScheduler threadPoolTaskScheduler;
public ScheduledFuture<?> job1;
public ScheduledFuture<?> job2;
#Autowired
ApplicationContext applicationContext;
#PostConstruct
public void job1() {
//NewDataCollectionThread thread1 = new NewDataCollectionThread();
NewDataCollectionThread thread1 = applicationContext.getBean(NewDataCollectionThread.class);
AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
factory.autowireBean(thread1);
factory.initializeBean(thread1, null);
job1 = threadPoolTaskScheduler.scheduleAtFixedRate(thread1, 1000);
}
}
This is a thread trying to call from scheduler. I tried to create service instance forcibly by using application context but it's not created.
#Configurable
#Scope("prototype")
public class NewDataCollectionThread implements Runnable {
private static final Logger LOGGER =
LoggerFactory.getLogger(NewDataCollectionThread.class);
#Autowired
private ExampleService exampleService;
#Override
public void run() {
LOGGER.info("Called from thread : NewDataCollectionThread");
System.out.println(Thread.currentThread().getName() + " The Task1
executed at " + new Date());
try {
exampleService.setRepository("sdasdasd");
System.out.println("Service Name :: " +
exampleService.getServiceName());
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Kindly suggest what are the possible ways to achieve it.
Try something like this:
#Autowired
private AutowireCapableBeanFactory beanFactory;
#PostConstruct
public void job1() {
NewDataCollectionThread thread1 = new NewDataCollectionThread();
beanFactory.autowireBean(thread1);
job1 = threadPoolTaskScheduler.scheduleAtFixedRate(thread1, 1000);
}
In NewDataCollectionThread I injected the Example service successfully.
It is the first time i use concurrency with Spring and i have a piece of code that makes concurrent calculations using Spring. Here is the code :
#Component
public class AppScheduler {
//#Autowired DAOs or services.
private ThreadPoolExecutor executor;
private AbstractApplicationContext context;
#PostConstruct
public void init() {
executor = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10));
context = new AnnotationConfigApplicationContext(VtmDispatcherConfig.class);
}
#Scheduled(fixedDelay = 60 * 1000)
//at rejection break the execution.
public void appEntry() {
//fetch some records from db
for (Record rec : records) {
try {
executeTransactionally(rec);
} catch (RejectedExecutionException ex) {
break;
}
}
}
#Transactional
//Creates runnable tasks, makes some db operations and passes task to the thread pool
private void executeTransactionally(Record rec) {
ARunnableTask aRunnableTask = (ARunnableTask) context.getBean("aRunnableTask");
aRunnableTask.setParameter(rec.param);
//some db operations...
tempTableExecutorPool.execute(aRunnableTask);
}
}
Here a scheduled code fetchs records from db and with each record instantiates a runnable task and passes it to the thread pool executor. And my runnable task is here :
#Component
#Scope("prototype")
public class ARunnableTask implements Runnable {
private String param;
private ThreadPoolExecutor executor;
private DAOOrService inject
#Autowired
public TempTableExecutorTask(DAOOrService inject) {
executor = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1000));
this.inject = inject;
}
#Override
public void run() {
//...
executeTransactional();
//...
executor.shutdown();
}
#Transactional
private void executeTransactional() {
//some transactional processes
}
public void setParameter(String param) {
this.param = param;
}
}
and here is my question : Is it a good practice creating runnable tasks as a spring component and using #Transactional in a runnable?
If it is not a bad practice, is there a better way for creating runnable spring components than :
ARunnableTask aRunnableTask = (ARunnableTask) context.getBean("aRunnableTask");
aRunnableTask.setParameter(rec.param);
I have created a simple scheduled task using Spring Framework's #Scheduled annotation.
#Scheduled(fixedRate = 2000)
public void doSomething() {}
Now I want to stop this task, when no longer needed.
I know there could be one alternative to check one conditional flag at the start of this method, but this will not stop execution of this method.
Is there anything Spring provides to stop #Scheduled task ?
Option 1: Using a post processor
Supply ScheduledAnnotationBeanPostProcessor and explicitly invoke postProcessBeforeDestruction(Object bean, String beanName), for the bean whose scheduling should be stopped.
Option 2: Maintaining a map of target beans to its Future
private final Map<Object, ScheduledFuture<?>> scheduledTasks =
new IdentityHashMap<>();
#Scheduled(fixedRate = 2000)
public void fixedRateJob() {
System.out.println("Something to be done every 2 secs");
}
#Bean
public TaskScheduler poolScheduler() {
return new CustomTaskScheduler();
}
class CustomTaskScheduler extends ThreadPoolTaskScheduler {
#Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, period);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);
return future;
}
#Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, startTime, period);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);
return future;
}
}
When the scheduling for a bean has to be stopped, you can lookup the map to get the corresponding Future to it and explicitly cancel it.
Here is an example where we can stop , start , and list also all the scheduled running tasks:
#RestController
#RequestMapping("/test")
public class TestController {
private static final String SCHEDULED_TASKS = "scheduledTasks";
#Autowired
private ScheduledAnnotationBeanPostProcessor postProcessor;
#Autowired
private ScheduledTasks scheduledTasks;
#Autowired
private ObjectMapper objectMapper;
#GetMapping(value = "/stopScheduler")
public String stopSchedule(){
postProcessor.postProcessBeforeDestruction(scheduledTasks, SCHEDULED_TASKS);
return "OK";
}
#GetMapping(value = "/startScheduler")
public String startSchedule(){
postProcessor.postProcessAfterInitialization(scheduledTasks, SCHEDULED_TASKS);
return "OK";
}
#GetMapping(value = "/listScheduler")
public String listSchedules() throws JsonProcessingException{
Set<ScheduledTask> setTasks = postProcessor.getScheduledTasks();
if(!setTasks.isEmpty()){
return objectMapper.writeValueAsString(setTasks);
}else{
return "No running tasks !";
}
}
}
Some time ago I had this requirement in my project that any component should be able to create a new scheduled task or to stop the scheduler (all tasks). So I did something like this
#Configuration
#EnableScheduling
#ComponentScan
#Component
public class CentralScheduler {
private static AnnotationConfigApplicationContext CONTEXT = null;
#Autowired
private ThreadPoolTaskScheduler scheduler;
public static CentralScheduler getInstance() {
if (!isValidBean()) {
CONTEXT = new AnnotationConfigApplicationContext(CentralScheduler.class);
}
return CONTEXT.getBean(CentralScheduler.class);
}
#Bean
public ThreadPoolTaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
public void start(Runnable task, String scheduleExpression) throws Exception {
scheduler.schedule(task, new CronTrigger(scheduleExpression));
}
public void start(Runnable task, Long delay) throws Exception {
scheduler.scheduleWithFixedDelay(task, delay);
}
public void stopAll() {
scheduler.shutdown();
CONTEXT.close();
}
private static boolean isValidBean() {
if (CONTEXT == null || !CONTEXT.isActive()) {
return false;
}
try {
CONTEXT.getBean(CentralScheduler.class);
} catch (NoSuchBeanDefinitionException ex) {
return false;
}
return true;
}
}
So I can do things like
Runnable task = new MyTask();
CentralScheduler.getInstance().start(task, 30_000L);
CentralScheduler.getInstance().stopAll();
Have in mind that, for some reasons, I did it without having to worry about concurrency. There should be some synchronization otherwise.
A working example implementation of #Mahesh 's Option 1, using ScheduledAnnotationBeanPostProcessor.postProcessBeforeDestruction(bean, beanName).
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
public class ScheduledTaskExample implements ApplicationContextAware, BeanNameAware
{
private ApplicationContext applicationContext;
private String beanName;
#Scheduled(fixedDelay = 1000)
public void someTask()
{
/* Do stuff */
if (stopScheduledTaskCondition)
{
stopScheduledTask();
}
}
private void stopScheduledTask()
{
ScheduledAnnotationBeanPostProcessor bean = applicationContext.getBean(ScheduledAnnotationBeanPostProcessor.class);
bean.postProcessBeforeDestruction(this, beanName);
}
#Override
public void setApplicationContext(ApplicationContext applicationContext)
{
this.applicationContext = applicationContext;
}
#Override
public void setBeanName(String beanName)
{
this.beanName = beanName;
}
}
There is a bit of ambiguity in this question
When you say "stop this task", did you mean to stop in such a way that it's later recoverable (if yes, programmatically, using a condition which arises with in the same app? or external condition?)
Are you running any other tasks in the same context? (Possibility of shutting down the entire app rather than a task) -- You can make use of actuator.shutdown endpoint in this scenario
My best guess is, you are looking to shutdown a task using a condition that may arise with in the same app, in a recoverable fashion. I will try to answer based on this assumption.
This is the simplest possible solution that I can think of, However I will make some improvements like early return rather than nested ifs
#Component
public class SomeScheduledJob implements Job {
private static final Logger LOGGER = LoggerFactory.getLogger(SomeScheduledJob.class);
#Value("${jobs.mediafiles.imagesPurgeJob.enable}")
private boolean imagesPurgeJobEnable;
#Override
#Scheduled(cron = "${jobs.mediafiles.imagesPurgeJob.schedule}")
public void execute() {
if(!imagesPurgeJobEnable){
return;
}
Do your conditional job here...
}
Properties for the above code
jobs.mediafiles.imagesPurgeJob.enable=true or false
jobs.mediafiles.imagesPurgeJob.schedule=0 0 0/12 * * ?
Another approach that I have not found yet. Simple, clear and thread safe.
In your configuration class add annotation:
#EnableScheduling
This and next step in your class where you need start/stop scheduled task inject:
#Autowired TaskScheduler taskScheduler;
Set fields:
private ScheduledFuture yourTaskState;
private long fixedRate = 1000L;
Create inner class that execute scheduled tasks eg.:
class ScheduledTaskExecutor implements Runnable{
#Override
public void run() {
// task to be executed
}
}
Add start() method:
public void start(){
yourTaskState = taskScheduler.scheduleAtFixedRate(new ScheduledTaskExecutor(), fixedRate);
}
Add stop() method:
public void stop(){
yourTaskState.cancel(false);
}
TaskScheduler provide other common way for scheduling like: cron or delay.
ScheduledFuture provide also isCancelled();
Minimalist answer:
#mahesh's option 1, expanded here in minimal form for convenience, will irreversibly cancel all scheduled tasks on this bean:
#Autowired
private ScheduledAnnotationBeanPostProcessor postProcessor;
#Scheduled(fixedRate = 2000)
public void doSomething() {}
public void stopThis() {
postProcessBeforeDestruction(this, "")
}
Alternatively, this will irreversibly cancel all tasks on all beans:
#Autowired
private ThreadPoolTaskScheduler scheduler;
#Scheduled(fixedRate = 2000)
public void doSomething() {}
public void stopAll() {
scheduler.shutdown();
}
Thanks, all the previous responders, for solving this one for me.
Scheduled
When spring process Scheduled, it will iterate each method annotated this annotation and organize tasks by beans as the following source shows:
private final Map<Object, Set<ScheduledTask>> scheduledTasks =
new IdentityHashMap<Object, Set<ScheduledTask>>(16);
Cancel
If you just want to cancel the a repeated scheduled task, you can just do like following (here is a runnable demo in my repo):
#Autowired
private ScheduledAnnotationBeanPostProcessor postProcessor;
#Autowired
private TestSchedule testSchedule;
public void later() {
postProcessor.postProcessBeforeDestruction(test, "testSchedule");
}
Notice
It will find this beans's ScheduledTask and cancel it one by one. What should be noticed is it will also stopping the current running method (as postProcessBeforeDestruction source shows).
synchronized (this.scheduledTasks) {
tasks = this.scheduledTasks.remove(bean); // remove from future running
}
if (tasks != null) {
for (ScheduledTask task : tasks) {
task.cancel(); // cancel current running method
}
}
Define a custom annotation like below.
#Documented
#Retention (RUNTIME)
#Target(ElementType.TYPE)
public #interface ScheduledSwitch {
// do nothing
}
Define a class implements org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.
public class ScheduledAnnotationBeanPostProcessorCustom
extends ScheduledAnnotationBeanPostProcessor {
#Value(value = "${prevent.scheduled.tasks:false}")
private boolean preventScheduledTasks;
private Map<Object, String> beans = new HashMap<>();
private final ReentrantLock lock = new ReentrantLock(true);
#Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
ScheduledSwitch switch = AopProxyUtils.ultimateTargetClass(bean)
.getAnnotation(ScheduledSwitch.class);
if (null != switch) {
beans.put(bean, beanName);
if (preventScheduledTasks) {
return bean;
}
}
return super.postProcessAfterInitialization(bean, beanName);
}
public void stop() {
lock.lock();
try {
for (Map.Entry<Object, String> entry : beans.entrySet()) {
postProcessBeforeDestruction(entry.getKey(), entry.getValue());
}
} finally {
lock.unlock();
}
}
public void start() {
lock.lock();
try {
for (Map.Entry<Object, String> entry : beans.entrySet()) {
if (!requiresDestruction(entry.getKey())) {
super.postProcessAfterInitialization(
entry.getKey(), entry.getValue());
}
}
} finally {
lock.unlock();
}
}
}
Replace ScheduledAnnotationBeanPostProcessor bean by the custom bean in configuration.
#Configuration
public class ScheduledConfig {
#Bean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
#Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor() {
return new ScheduledAnnotationBeanPostProcessorCustom();
}
}
Add #ScheduledSwitch annotation to the beans that you want to prevent or stop #Scheduled tasks.
Using #conditional will help you check a value from condition method, if it's true? run the scheduler. else don't run.
First: create your condition class that implements the Condition interface and its matches method
public class MyCondition implements Condition{
public boolean matches(ConditionContext context, AnnotatedTypeMetaData metadata) {
// here implement your condition using if-else or checking another object
// or call another method that can return boolean value
//return boolean value : true or false
return true;
}
}
Then, back to your configuration or service class where you have the #Scheduled
#Service
#Conditional(value = MyCondition.class)
// this Service will only run if the condition is true
public class scheduledTask {
// the #Scheduled method should be void
#Scheduled(fixedRate= 5000)
public void task(){
System.out.println(" This is scheduled task started....");
}
}
This definitely worked for me.
import com.google.common.collect.Maps;
import org.redisson.liveobject.misc.ClassUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
import static java.util.Collections.emptySet;
import com.google.common.collect.Maps;
import org.redisson.liveobject.misc.ClassUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
import static java.util.Collections.emptySet;
/**
* #author uhfun
*/
#Component
public class ConfigurableScheduler {
private final InnerScheduledAnnotationBeanPostProcessor postProcessor;
public ConfigurableScheduler(InnerScheduledAnnotationBeanPostProcessor postProcessor) {
this.postProcessor = postProcessor;
}
public void registerScheduleTask(String cron, Method method, Object target) {
Map<String, Object> attributes = Maps.newHashMap();
attributes.put("cron", cron);
Scheduled scheduled = AnnotationUtils.synthesizeAnnotation(attributes, Scheduled.class, null);
postProcessor.registerScheduleTask(scheduled, method, target);
}
public void unregister(String cron, Object target) {
postProcessor.unregister(target, cron);
}
#Component
public static class InnerScheduledAnnotationBeanPostProcessor extends ScheduledAnnotationBeanPostProcessor {
private final Map<Object, Set<ScheduledTask>> scheduledTasksMap;
public InnerScheduledAnnotationBeanPostProcessor() {
scheduledTasksMap = ClassUtils.getField(this, "scheduledTasks");
}
public void registerScheduleTask(Scheduled scheduled, Method method, Object bean) {
super.processScheduled(scheduled, method, bean);
}
public void unregister(Object bean, String cron) {
synchronized (scheduledTasksMap) {
Set<ScheduledTask> tasks = getScheduledTasks();
for (ScheduledTask task : tasks) {
if (task.getTask() instanceof CronTask
&& ((CronTask) task.getTask()).getExpression().equals(cron)) {
task.cancel();
scheduledTasksMap.getOrDefault(bean, emptySet()).remove(task);
}
}
}
}
}
}
How about using System.exit(1)?
It is simple and works.
I am using Spring 4. I use this for execute a task periodically for web sockets:
private TaskScheduler scheduler = new ConcurrentTaskScheduler();
In my class:
#Configuration
#EnableWebSocketMessageBroker
#EnableScheduling
#Component
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Autowired
private SimpMessagingTemplate template;
private TaskScheduler scheduler = new ConcurrentTaskScheduler();
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/simplemessages").withSockJS();
}
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic/", "/queue/");
config.setApplicationDestinationPrefixes("/app");
}
#PostConstruct
private void broadcastTimePeriodically() {
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
String statStr = "Server Response" + new Date();
System.out.println("thread schedular run time :" + Hello.printTime());
try {
template.convertAndSend("/topic/simplemessagesresponse", statStr);
} catch (MessagingException e) {
System.err.println("!!!!!! websocket timer error :>" + e.toString());
}
}
}, 4000));
}
#PreDestroy
private void destroyServices() {
scheduler = null; // how to destroy ?
}
public void configureClientInboundChannel(ChannelRegistration registration) {
}
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.taskExecutor().corePoolSize(4).maxPoolSize(10);
}
public boolean configureMessageConverters(List < MessageConverter > arg0) {
// TODO Auto-generated method stub
return true;
}
#Override
public void configureWebSocketTransport(WebSocketTransportRegistration arg0) {
}
}
I want to know to things:
I found that the scheduler is running twice within 4000 milliseconds. How is it happening and how can I stop it?
I run this application in tomcat. As you can see, the method destroyServices() needs to destroy the schedular. Here the problem is, even the tomcat is restarted again, previously running thread is still running. So when the tomcat is going to down, that thread also should be terminated. I need to know How I can destroy it on tomcat is going to down or any system crash?
The following code snippet is from documentation of #EnableScheduling:
#Configuration
#EnableScheduling
public class AppConfig implements SchedulingConfigurer {
#Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
#Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(100);
}
}
I think you should get the bean named taskExecutor (in this case) and call shutdown (in fact depending on your configuration) method of it.