What is the better way to stop currently running job in quartz scheduler? - quartz-scheduler

I am using quartz Scheduler .I want to stop currently running job.
I am using this one in a web application .When I click on start button then job execution is started but when I want to stop this executing job using stop button .
But I am not able to stop.
Please give me an idea how can I stop currently running job?
I am giving my code.
//when i click on start button then this class will call.
#WebServlet("/ScheduleController")
public class AscentScheduleController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String RANDOM = "random";
Scheduler schedulerRecon;
Scheduler schedulerPos;
Scheduler schedulerFile;
Scheduler schedulerEtl;
Trigger triggerIris;
JobKey jobKey;
JobDetail job;
String key;
int time;
/**
* #see HttpServlet#HttpServlet()
*/
public AscentScheduleController() {
super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
HttpSession session = request.getSession();
try {
String id = request.getParameter("id");
System.out.println("hello in controller");
System.out.println(id);
System.out.println(Thread.currentThread().getName());
schedulerRecon = new StdSchedulerFactory()
.getScheduler();
schedulerRecon.start();
session.setAttribute(id,schedulerRecon );
System.out.println();// SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever()).build();
System.out.println();
System.out.println();
System.out.println("controller schedil "+schedulerRecon);
System.out.println(Thread.currentThread().getName());
jobKey = new JobKey("jobKeyIris", "group1");
job = JobBuilder.newJob(DemoTrgger.class).withIdentity("jobKey").build();
triggerIris = TriggerBuilder.newTrigger().withIdentity("triggerIris", "group1").startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(60).// repeatForever()).build();
withRepeatCount(0)).build();
session.setAttribute("job", jobKey);
System.out.println();// SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever()).build();
System.out.println();
System.out.println();
System.out.println("controller job key "+jobKey);
// temp=temp+temp;
schedulerRecon.scheduleJob(job, triggerIris);
// scheduler.scheduleJob(jobQCB, triggerQCB);
System.out.println("fire job");
}
}
//and my job class which implement Job is below
public class DemoTrgger implements Job {
public static Thread th;
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println();
System.out.println("demo trigger "+Thread.currentThread().getName()+"thread obj "+Thread.currentThread());
th = Thread.currentThread();
System.out.println();
for(long i=0l;i<2000000;i++){
System.out.println("i--------- "+i);
}
for(long i=0l;i<2000000l;i++){
System.out.println("j--- "+i);
}
}
}
when I click on stop button the below class will call.Here I get the Scheduler reference which I use in start using session and I want stop respectively running job.
#WebServlet("/SchedulerStopController")
public class SchedulerStopController extends HttpServlet implements InterruptableJob {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SchedulerStopController() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id=request.getParameter("id");
System.out.println(id);
HttpSession session=request.getSession();
Scheduler schedular=(Scheduler) session.getAttribute(id);
System.out.println();// SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever()).build();
System.out.println();
System.out.println();
System.out.println("stop schedular "+schedular);
try {
SchedulerMetaData metaData = schedular.getMetaData();
} catch (SchedulerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
/*Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
System.out.println(Thread.currentThread().getName());
// this will get called on shutdown
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("------- My own shutdown hook -----------------");
}
});
*/
try {
JobKey jobKey=(JobKey) session.getAttribute("job");
System.out.println();// SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever()).build();
System.out.println();
System.out.println("stop controller "+Thread.currentThread().getName());
System.out.println();
System.out.println("stop job "+jobKey);
schedular.deleteJob(jobKey);
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
thanks.

Related

Repository.Save() inside scheduling is not working

I have a repository.save() method called inside a scheduler. But it is not saving anything to the database.
Following is my scheduler
#Component
#Transactional
#Slf4j
public class WomConditionActionJob {
#Autowired
private Environment env;
#Autowired
private ECCRepository eCCRepository;
#Autowired
private WOCRepository wOCRepository;
#Autowired
private PSRepository pSRepository;
#Scheduled(fixedDelayString = "${wCATrigger.polling.frequency}", initialDelayString = "${wCATrigger.initial.delay}")
public void execute() {
try {
final PauseStatus pause = pSRepository.findByPSName(PSName.PAUSE);
pauseCondition(pause,threshold);
} catch (Exception e) {
log.error("Exception Occured {}", e);
}
}
private void pauseCondition(final PauseStatus pause, final Integer threshold) {
WOTCondition wotCId = workOrderConditionRepository.findById(1).get();
wotCId.setPauseStatus(pause);
wotCId.setIsUserAction(Boolean.FALSE);
workOrderConditionRepository.save(wotConditionbyId);
conditionCount.setErrorCount(0);
errorConditionCountRepository.save(conditionCount);
}
}
I trying using saveAndFlush() but that time I got Following error
[pool-2-thread-1]|ERROR|[o.s.s.s.TaskUtils$LoggingErrorHandler.handleError(96)]|Unexpected error occurred in scheduled task.
org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:873)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:710)
Adding this solved my issue
#Transactional(propagation=Propagation.REQUIRES_NEW)
Example
#Scheduled(cron = "0/5 * * * * *")
#Transactional(propagation=Propagation.REQUIRES_NEW)
#Override
public void scheduleJob() {
Message message = new Message();
message.setMessageId(UUID.randomUUID().toString());
message.setAccountId("accountId");
message.setSent(2L);
message.setFailed(2L);
message.setDelivered(2L);
// saves or update message_report table
messageRepository.save(message);
}

Connection leakage issue when static method called from spring transactional method

I have a transactional method at Service layer which call a static method where i am starting a thread for some async task(again some database operation). Does calling a static method from transactional scope can make some db connection leakage problem ?
Below is a sample code explaining the use case.
#Override
#Transactional
public void createRecords(Record r1, Record r2, HttpServletRequest request) {
saveSomeData(r1,r2.getScore());
// Call a Static Method that open a seperate thread
AsyncTasker.doSomeThing(r2);
saveNewData(r2);
}
AsyncTasker.java
public class AsyncTasker {
private static final Logger logger = LoggerFactory.getLogger(AsyncTasker.class);
private static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void doSomeThing(Record r){
try{
ClearTask clearTask = new ClearTask(r);
executorService.submit(clearTask);
}
catch(Exception e){
logger.error("Error in ClearTask task execution " + r +" : Exception "+ e);
}
}
}
class ClearTask implements Runnable{
private Record r;
ClearTask(Record r){
this.r = r;
}
#Override`enter code here`
public void run() {
Token.deleteAllData(r); // Static method making a rest call
}
}

Handling multiple client in java

I made simple client server chat program that support multiple client but i have a problem:`
public class Main extends Application {
public Button send;
public TextArea textarea;
public TextArea onlineuser;
public TextField usertext;
public static int maxUser = 100;
public boolean run=true;
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("server.fxml"));
primaryStage.setTitle("Server control ");
primaryStage.setScene(new Scene(root, 749, 494));
primaryStage.show();
}
public static void main(String[] args) throws IOException{
Server sv=new Server(1111);
launch(args);
}
class Server extends Thread {
private ServerSocket sv;
private ThreadServer[] clientconnect = new ThreadServer[maxUser];
public Server(int port) throws IOException {
this.sv = new ServerSocket(port);
start();
}
public void run() {
while (run) {
try {
Socket connect = this.sv.accept();
connectionThread(connect);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void connectionThread(Socket connection) {
for (int a = 0; a < maxUser; a++) {
if (this.clientconnect[a] == null) {
this.clientconnect[a] = new ThreadServer(connection, a);
break;
}
}
}
}
class ThreadServer extends Thread {
final private int userID;
final private Socket threadconnect;
public void run() {
while (run)) {
try {
PrintWriter out = new PrintWriter(threadconnect.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(threadconnect.getInputStream()));
textarea.appendText(in.readLine());
out.println(usertext.getText());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public ThreadServer(Socket connect, int ID) {
this.userID = ID;
this.threadconnect = connect;
}
}
I have client part works fine but i cant call my server class in main because it's not a static but i should use main also launch javafx gui part how can i solve this problem?

Play2 How to manage the transaction from the service layer instead of action layer?

I am using Play2.1.1 Java with JPA2.0 with hibernate implementation.
to control the transaction by code instead of using #transactional like below is the normal JPA code style, Is there any way to work like below at Play? or how to use JPA.withtranaction() to do? I tried it, no idea how to pass in the parameter, I am not familiar with functional code. thanks a lot. Please give me some sample code based on below.
public void createActorB(final String email, final String psw) throws Throwable {
EntityManager manager = JPA.em();
try {
EntityTransaction ex = manager.getTransaction();
this.dbActor.setEmail(email);
this.dbActor.setCredential(psw);
manager.persist(this.dbActor);
ex.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new ActorException(CODE.UNKNOWN, e);
} finally {
manager.close();
}
}
Now I change my code below to start transaction from service layer, It does not looks efficient, is there any other way to write? thanks
private void internalCreateActor(String email, String psw) throws ActorException {
if (StringUtils.isEmpty(email) || StringUtils.isEmpty(psw))
throw new ActorException(CODE.INVALIDE_PARAMETER);
try {
this.dbActor.setEmail(email);
this.dbActor.setCredential(psw);
this.dbActor.setCreateD(new Date());
JPA.em().persist(this.dbActor);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new ActorException(CODE.UNKNOWN, e);
}
}
public void createActor(final String email, final String psw, final String cellPhone, final Actor.TYPE type)
throws Throwable {
JPA.withTransaction(new Callback0() {
#Override
public void invoke() throws Throwable {
internalCreateActor(email, psw, cellPhone, type);
}
});
}
something like this:
public static User getUserByIdentity(final AuthUserIdentity identity) {
try {
return JPA.withTransaction(new play.libs.F.Function0<User>() {
public User apply() {
return User.findByAuthUserIdentity(identity);
}
});
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
After some time research, I write a method JPAUtil referring to JPA provided by Play which can use normally to control the transaction manually from the service layer actually everywhere.
public class JPAUtil {
static ThreadLocal<EntityManager> currentEntityManager = new ThreadLocal<EntityManager>();
/**
* Get the EntityManager for specified persistence unit for this thread.
*/
public static EntityManager em(String key) {
Application app = Play.application();
if (app == null) {
throw new RuntimeException("No application running");
}
JPAPlugin jpaPlugin = app.plugin(JPAPlugin.class);
if (jpaPlugin == null) {
throw new RuntimeException("No JPA EntityManagerFactory configured for name [" + key + "]");
}
EntityManager em = jpaPlugin.em(key);
if (em == null) {
throw new RuntimeException("No JPA EntityManagerFactory configured for name [" + key + "]");
}
bindForCurrentThread(em);
return em;
}
/**
* Get the default EntityManager for this thread.
*/
public static EntityManager em() {
EntityManager em = currentEntityManager.get();
if (em == null) {
return em(Constants.DATASOURCEKEY);
}
return em;
}
/**
* Bind an EntityManager to the current thread.
*/
public static void bindForCurrentThread(EntityManager em) {
currentEntityManager.set(em);
}
public static void closeEM() {
EntityManager em = currentEntityManager.get();
if (em != null) {
em.close();
}
bindForCurrentThread(null);
}
public static void beginTransaction() {
em().getTransaction().begin();
}
public static void commitTransaction() {
em().getTransaction().commit();
}
}

GWT Void remote services fail for seemingly no reason

I'm working on a GWT project and have several void remote services that seem to execute just fine, but on the client side, end up firing the onFailure() method. No exceptions are thrown anywhere, and the expected behavior is observed on the backend. I have no idea what could be going wrong. Here is the relevant code:
Interfaces and implementation...
#RemoteServiceRelativePath("DeleteSearchService")
public interface DeleteSearchService extends RemoteService {
/**
* Utility class for simplifying access to the instance of async service.
*/
public static class Util {
private static DeleteSearchServiceAsync instance;
public static DeleteSearchServiceAsync getInstance(){
if (instance == null) {
instance = GWT.create(DeleteSearchService.class);
}
return instance;
}
}
public void delete(SearchBean search);
}
public interface DeleteSearchServiceAsync {
public void delete(SearchBean bean, AsyncCallback<Void> callback);
}
public class DeleteSearchServiceImpl extends RemoteServiceServlet implements DeleteSearchService {
private static final long serialVersionUID = 1L;
#Override
public void delete(SearchBean search) {
try {
Connection conn = SQLAccess.getConnection();
String sql = "DELETE FROM `searches` WHERE `id`=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, search.getSearchId());
ps.execute();
sql = "DELETE FROM `searchsourcemap` WHERE `search-id` = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, search.getSearchId());
ps.execute();
return;
} catch (Exception e) {
// TODO Log error
e.printStackTrace();
}
}
}
Calling code...
private class DeleteListener implements ClickListener {
public void onClick(Widget sender) {
DeleteSearchServiceAsync dss = DeleteSearchService.Util.getInstance();
SearchBean bean = buildBeanFromGUI();
dss.delete(bean, new AsyncCallback<Void>(){
//#Override
public void onFailure(Throwable caught) {
// TODO log
SearchNotDeleted snd = new SearchNotDeleted();
snd.show();
}
//#Override
public void onSuccess(Void result) {
SearchDeleted sd = new SearchDeleted();
sd.show();
searchDef.getParent().removeFromParent();
}
});
}
}
I know I'm a jerk for posting like 500 lines of code but I've been staring at this since yesterday and can't figure out where I'm going wrong. Maybe a 2nd set of eyes would help...
Thanks,
brian
LGTM I'm afraid.
Are you using the hosted mode or a full-fledged browser? You can try switching and see if it helps.
Also, it might help listening to that //TODO and perform a GWT.log when onFailure is invoked.