Skip to content

Instantly share code, notes, and snippets.

@bmchild
Created May 9, 2014 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmchild/b84ff01213ecc6505459 to your computer and use it in GitHub Desktop.
Save bmchild/b84ff01213ecc6505459 to your computer and use it in GitHub Desktop.
Manually execute a @scheduled method
package com.bmchild.controller.admin;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bmchild.model.ajax.BaseAjaxResponse;
/**
* @author bchild
*
*/
@Controller
@RequestMapping("/admin/scheduler")
//TODO @Secured
public class SchedulerController {
@Autowired
private ApplicationContext appContext;
@RequestMapping(value = "/execute", method = RequestMethod.POST)
@ResponseBody
public BaseAjaxResponse executeBean(@RequestParam("beanClass") String beanClass) {
BaseAjaxResponse response = new BaseAjaxResponse();
Boolean destroyBean = false;
Object bean = null;
try {
Class<?> clazz = Class.forName(beanClass);
bean = getExistingBean(clazz);
if(bean == null) {
bean = appContext.getAutowireCapableBeanFactory().createBean(clazz);
destroyBean = true;
}
for(Method method : AopUtils.getTargetClass(bean).getMethods()) {
if(method.isAnnotationPresent(Scheduled.class)) {
method.invoke(bean);
response.setSuccess(Boolean.TRUE);
response.setSuccessMessage("scheduled method invoked");
break;
}
}
} catch(InvocationTargetException | IllegalAccessException | IllegalArgumentException | BeansException | IllegalStateException | ClassNotFoundException e) {
response.setErrorsSuccess(e.getClass().toString() + ": " + e.getMessage());
} finally {
if(destroyBean && bean != null) {
appContext.getAutowireCapableBeanFactory().destroyBean(bean);
}
}
return response;
}
private Object getExistingBean(Class<?> beanClass) throws ClassNotFoundException {
Object bean;
try {
bean = appContext.getBean(beanClass);
} catch(BeansException e) {
bean = null;
}
return bean;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment