Quartz 作业未在 java 网络中重新启动

Quartz job not restarting in java web

我正在实现一个模块,每 3 分钟截取一次登录用户的屏幕截图。

这个模块工作正常

但我面临的问题是,每当我登录用户时,作业都会按预期开始,但在注销时我会关闭调度程序。但是现在下次我尝试重新登录时,调度程序已初始化但作业没有开始。我需要为下一个 运行.

再次重新部署项目

这是我的 LoginBean.java class 我开始工作的地方。

package com.viremp.beans;

import java.awt.AWTException;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.viremp.component.HandleHobs;

@ManagedBean
@SessionScoped
public class LoginBean implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -8650636789236091591L;
private static Logger LOGGER = LoggerFactory.getLogger(LoginBean.class);

private String username;

private String password;

private String error;

private boolean visible = false;

private HandleHobs handleHobs;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getError() {
    return error;
}

public void setError(String error) {
    this.error = error;
}

public boolean isVisible() {
    return visible;
}

public void setVisible(boolean visible) {
    this.visible = visible;
}

/*
 * public LoginBean() { try { if (handleHobs != null &&
 * !handleHobs.isJobStoredScreenShotIsStarted()) { handleHobs = new
 * HandleHobs(); } } catch (Exception e) { LOGGER.error("error init job", e); }
 * 
 * }
 */

@PostConstruct
public void init() {
    try {
        if (handleHobs == null || !handleHobs.isJobStoredScreenShotIsStarted()) {
            handleHobs = new HandleHobs();
        }
    } catch (Exception e) {
        LOGGER.error("error init job", e);
    }

}

public void login() throws ClassNotFoundException, SQLException, IOException, AWTException {
    // String un = "a";
    // String pw = "b";
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    // Login login = new Login();
    // boolean isLoggedIn = login.LoginUser(username, password);
    try {
        request.login(username, password);

        handleHobs.startJobStoredScreenShot(username);
        externalContext
                .redirect(externalContext.getRequestContextPath() + "/faces/Success.xhtml?faces-redirect=true");
    } catch (Exception e) {
        FacesContext fc = FacesContext.getCurrentInstance();
        this.error = getErrorParam(fc);

        setVisible(true);
        System.out.println("not equal.. " + error);
        e.printStackTrace();
    }

    /*
     * 
     * if (isLoggedIn) { System.out.println("equal"); externalContext
     * .redirect(externalContext.getRequestContextPath() +
     * "/faces/Success.xhtml?faces-redirect=true"); } else {
     * 
     * FacesContext fc = FacesContext.getCurrentInstance(); this.error =
     * getErrorParam(fc);
     * 
     * setVisible(true); System.out.println("not equal.. " + error);
     * 
     * }
     */
}

public String getErrorParam(FacesContext fc) {

    Map<String, String> params = fc.getExternalContext().getRequestParameterMap();
    return params.get("error1");

}
public logout(){
      handleHobs.shutdownJobStoredScreenShot();
      ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    externalContext.invalidateSession();
    externalContext.redirect(externalContext.getRequestContextPath() + "/faces/login.xhtml?faces-redirect=true");
}

这里是我的HandleHobs.javaclass,是处理工作的,[抱歉打错了class名字,应该是HandleJobs.java]

package com.viremp.component;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HandleHobs {

private static Logger LOGGER = LoggerFactory.getLogger(HandleHobs.class);

private static JobDetail job;

private static Scheduler scheduler;
String email;

public HandleHobs(String email) {
    this.email = email;
}

private static Trigger trigger;

{
    try {

        if (job == null && scheduler == null && trigger == null) {
            LOGGER.info("initializing job");

            job = (JobDetail) newJob(JobStoredScreenShot.class).withIdentity("job1", "group1").build();

            trigger = newTrigger().withIdentity("trigger1", "group1").startNow()
                    .withSchedule(simpleSchedule().withIntervalInSeconds(5).repeatForever()).build();

            scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(job, trigger);
            LOGGER.info("init successsful");
        }
    } catch (Exception e) {
        LOGGER.error("fail to init variables for job", e);
    }
}

public HandleHobs() {

}

public void startJobStoredScreenShot(String email) {
    try {
        this.email = email;
        JobStoredScreenShot jss = new JobStoredScreenShot();
        jss.setEmail(email);
        if (scheduler != null && !scheduler.isStarted()) {

            Scheduler scheduler1 = new StdSchedulerFactory().getScheduler();
            System.out.println("here..... " + email);
            scheduler1.getContext().put("email", email);
            System.out.println("and here..... " + email);

            scheduler.start();
        }
        LOGGER.info("init successsful");
    } catch (Exception e) {
        LOGGER.error("fail to init job JobStoredScreenShot", e);
    }
}

public void shutdownJobStoredScreenShot() {
    try {
        if (scheduler.isStarted()) {
            scheduler.shutdown();
        }
        LOGGER.info("shutdown successsful");
    } catch (Exception e) {
        LOGGER.error("fail to init job JobStoredScreenShot", e);
    }
}

public boolean isJobStoredScreenShotIsStarted() {
    boolean isStarted = false;
    try {

        if (scheduler != null) {
            isStarted = true;
        }
    } catch (Exception e) {
        LOGGER.error("fail get isTarted", e);
    }
    return isStarted;
}

}

这是我的 JobStoredScreenShot.java class

package com.viremp.component;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.time.LocalDate;

import javax.imageio.ImageIO;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;

import com.viremp.core.domain.Screenshot;
import com.viremp.core.domain.User;
import com.viremp.core.repository.ScreenshotRepository;
import com.viremp.core.repository.UserRepository;
import com.viremp.core.repository.impl.ScreenshotRepositoryImpl;
import com.viremp.core.repository.impl.UserRepositoryImpl;

public class JobStoredScreenShot implements Job {

String email;
User user = new User();

public void setEmail(String Email) {

    this.email = Email;
    System.out.println("in job stored class email is: " + email);

    user.setEmail(email);
}

@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {

    try {

        SchedulerContext schedulerContext = arg0.getScheduler().getContext();
        // Below line gets the value from context.
        // Just get it and cast it in to correct type
        String email = (String) schedulerContext.get("email");
        System.out.println(email);
        BufferedImage image = new Robot()
                .createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();

        System.out.println("in execute " + user.getEmail() + ".................: " + email);
        UserRepository userRepository = new UserRepositoryImpl();
        user = userRepository.getUserByEmail(email);
        System.out.println("USER IS: " + user.getUsername() + " id is : " + user.getId());
        // byte[] buffer = (((DataBufferByte)
        // (image).getRaster().getDataBuffer()).getData());
        InputStream inputStream = new ByteArrayInputStream(imageInByte);
        LocalDate localDate = LocalDate.now();
        Screenshot screenshot = new Screenshot();
        screenshot.setInput(inputStream);
        screenshot.setScreenshotName(user.getUsername());
        screenshot.setUser(new User());
        screenshot.getUser().setId(user.getId());
        screenshot.setScreenShotTime(java.sql.Date.valueOf(localDate));
        System.out.println("id is " + 1l);
        ScreenshotRepository screenshotRepository = new ScreenshotRepositoryImpl();
        screenshotRepository.create(screenshot);
        ImageIO.write(image, "png", new File("d:\screenshot.png"));

        System.out.println("screenshot taken");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

请帮忙,谢谢

我通过在关闭 scheduler.

后使 jobscheduler null 解决了这个问题

这是HandleHobs.java

的工作代码
package com.viremp.component;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HandleHobs {
private static Logger LOGGER = LoggerFactory.getLogger(HandleHobs.class);

private static JobDetail job;

private static Scheduler scheduler;
String email;

// SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();

public HandleHobs(String email) {
    this.email = email;
}

private static Trigger trigger;

{
    try {

        LOGGER.info("initializing job");

        job = (JobDetail) newJob(JobStoredScreenShot.class).withIdentity("job1", "group1").build();

        trigger = newTrigger().withIdentity("trigger1", "group1").startNow()
                .withSchedule(simpleSchedule().withIntervalInSeconds(5).repeatForever()).build();

        scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.scheduleJob(job, trigger);
        LOGGER.info("init successsful 1");
    } catch (Exception e) {
        LOGGER.error("fail to init variables for job", e);
    }
}

public HandleHobs() {

}

public void startJobStoredScreenShot(String email) {
    try {
        System.out.println("yaar ma aa gaya hun");
        this.email = email;
        JobStoredScreenShot jss = new JobStoredScreenShot();
        jss.setEmail(email);
        if (scheduler != null && !scheduler.isStarted()) {

            Scheduler scheduler1 = new StdSchedulerFactory().getScheduler();
            System.out.println("here..... " + email);
            scheduler1.getContext().put("email", email);
            System.out.println("and here..... " + email);
            scheduler.start();

        }
        LOGGER.info("init successsful");
    } catch (Exception e) {
        LOGGER.error("fail to init job JobStoredScreenShot", e);
    }
}

public void shutdownJobStoredScreenShot() {
    try {
        if (scheduler.isStarted()) {
            // JobExecutionContext context = new JobExecutionContext();
            // JobKey key = context.getJobDetail().getKey();
            // String jobId = key.getName();
            // System.out.println("```````````````````NAME``````````````````````" + jobId);
            // flag = true;

            scheduler.shutdown();
            scheduler = null;  //i made it null here
            job = null; // i made it null here
        }
        LOGGER.info("shutdown successsful");
    } catch (Exception e) {
        LOGGER.error("fail to init job JobStoredScreenShot", e);
    }
}

public boolean isJobStoredScreenShotIsStarted() {
    boolean isStarted = false;
    try {

        if (scheduler != null) {
            isStarted = true;
        }
    } catch (Exception e) {
        LOGGER.error("fail get isTarted", e);
    }
    return isStarted;
}

}

这是我 LoginBean.java 开始工作的地方。

package com.viremp.beans;

import java.awt.AWTException;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.viremp.component.HandleHobs;

@ManagedBean
@SessionScoped
public class LoginBean implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -8650636789236091591L;

private static Logger LOGGER = LoggerFactory.getLogger(LoginBean.class);

private String username;

private String password;

private String error;

private boolean visible = false;

private HandleHobs handleHobs;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getError() {
    return error;
}

public void setError(String error) {
    this.error = error;
}

public boolean isVisible() {
    return visible;
}

public void setVisible(boolean visible) {
    this.visible = visible;
}

/*
 * public LoginBean() { try { if (handleHobs != null &&
 * !handleHobs.isJobStoredScreenShotIsStarted()) { handleHobs = new
 * HandleHobs(); } } catch (Exception e) { LOGGER.error("error init job", e); }
 * 
 * }
 */

@PostConstruct
public void init() {
    try {

        handleHobs = new HandleHobs();

    } catch (Exception e) {
        LOGGER.error("error init job", e);
    }

}

public void login() throws ClassNotFoundException, SQLException, IOException, AWTException {
    // String un = "a";
    // String pw = "b";
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    // Login login = new Login();
    // boolean isLoggedIn = login.LoginUser(username, password);
    try {
        request.login(username, password);

        handleHobs.startJobStoredScreenShot(username);
        externalContext
                .redirect(externalContext.getRequestContextPath() + "/faces/Success.xhtml?faces-redirect=true");
    } catch (Exception e) {
        FacesContext fc = FacesContext.getCurrentInstance();
        this.error = getErrorParam(fc);

        setVisible(true);
        System.out.println("not equal.. " + error);
        e.printStackTrace();
    }

    /*
     * 
     * if (isLoggedIn) { System.out.println("equal"); externalContext
     * .redirect(externalContext.getRequestContextPath() +
     * "/faces/Success.xhtml?faces-redirect=true"); } else {
     * 
     * FacesContext fc = FacesContext.getCurrentInstance(); this.error =
     * getErrorParam(fc);
     * 
     * setVisible(true); System.out.println("not equal.. " + error);
     * 
     * }
     */
}

public void logout() {

    System.out.println("in logotu");
    handleHobs.shutdownJobStoredScreenShot();
    this.handleHobs = null; // here i also made null
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    externalContext.invalidateSession();
    try {
        externalContext
                .redirect(externalContext.getRequestContextPath() + "/faces/Login.xhtml?faces-redirect=true");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public String getErrorParam(FacesContext fc) {

    Map<String, String> params = fc.getExternalContext().getRequestParameterMap();
    return params.get("error1");

}
}

实际上在关闭作业后确实关闭了调度程序但没有清空作业和调度程序,所以在下次登录时调度程序和作业保留值以便作业不会再次启动,所以我只是设置了值关机时为空。