JFinal定时任务的配置

1 篇文章 0 订阅

最近在使用JFinal的框架,之前使用spring框架,直接在配置文件配置下就可以了。所以从网上找了相关例子,整理了一下

1.建一个配置文件job.properties,用作定时配置

job=com.demo.job.JobA
cron=* * 2 * * ?
enable=true
上面是一个定时任务,如果需要多个,从后面展示的定时读取可知,这么配置一下就可以了

bjob=com.demo.job.JobB
bcron=* * 2 * * ?
benable=true

对应执行的任务类的包名配置好,定时时间配置好就行了,一定要把XXXenable设置成true(开启状态)

对于定时设置,参考:quartz 时间配置 就可以了


2.定时执行的类

比如刚才把com.demo.job.JobA弄好了,于是在该类下,代码如下:

public class JobA implements Job{
	private static Logger log = Logger.getLogger(JobA.class);
	
	/**
	 * 执行定时任务
	 */
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		System.out.println("我被执行了");
	}
	
}
里面具体内容就不用我说了

3.定时类

需要读取刚才写好的job.properties,具体怎么读可以自己改写,我是这么做的(也是改的)

/**
 * 实现作业的调度
 * 
 * @author jerri liu
 */
public class NewQuartzPlugin implements IPlugin {

	private Logger logger = LoggerFactory.getLogger(getClass());
	private SchedulerFactory sf = null;
	private Scheduler sched = null;
	private String config = "job.properties";
	private Properties properties;
	
	public NewQuartzPlugin(String config) {
		this.config = config;
	}
	public NewQuartzPlugin() {
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean start() {
		sf = new StdSchedulerFactory();
		try {
			sched = sf.getScheduler();
		}
		catch (SchedulerException e) {
			new RuntimeException(e);
		}
		loadProperties();
		Enumeration enums = properties.keys();
		while (enums.hasMoreElements()) {
			String key = enums.nextElement() + "";
			if (!key.endsWith("job")) {
				continue;
			}
			String cronKey = key.substring(0, key.indexOf("job")) + "cron";
			String enable = key.substring(0, key.indexOf("job")) + "enable";
			if (isDisableJob(enable)) {
				continue;
			}
			String jobClassName = properties.get(key) + "";
			String jobCronExp = properties.getProperty(cronKey) + "";
			Class clazz;
			try {
				clazz = Class.forName(jobClassName);
			}
			catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
			JobDetail job = newJob(clazz).withIdentity(jobClassName, jobClassName).build();
			CronTrigger trigger = newTrigger().withIdentity(jobClassName, jobClassName).withSchedule(cronSchedule(jobCronExp)).build();
			Date ft = null;
			try {
				ft = sched.scheduleJob(job, trigger);
				sched.start();
			}
			catch (SchedulerException ee) {
				new RuntimeException(ee);
			}
			logger.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.getCronExpression());
		}
		return true;
	}

	private boolean isDisableJob(String enable) {
		return Boolean.valueOf(properties.get(enable) + "") == false;
	}

	private void loadProperties() {
		properties = new Properties();
		InputStream is = NewQuartzPlugin.class.getClassLoader().getResourceAsStream(config);
		try {
			properties.load(is);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public boolean stop() {
		try {
			sched.shutdown();
		}
		catch (SchedulerException e) {
			logger.error("shutdown error", e);
			return false;
		}
		return true;
	}

	public static void main(String[] args) {
		NewQuartzPlugin plugin = new NewQuartzPlugin();
		plugin.start();
		System.out.println("执行成功!!!");

	}
}

代码很好看懂,就是遍历读这三个配置(可能多个任务),然后根据启动状态分别去执行这几个任务

4.在插件中引入这个定时插件

// quartz插件
NewQuartzPlugin quartzPlugin =  new NewQuartzPlugin("job.properties");
me.add(quartzPlugin);
具体位置如下



这样,定时器就配置好了,我设置的是每天早上2点执行该任务(当然公司需要,展示的空代码,需自己填充)

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
JFinal 框架本身没有提供定时任务功能,但是可以通过集成第三方库来实现定时任务。下面介绍两种实现方式: 1. 使用Quartz定时任务 Quartz 是一个开源的 Java 定时任务框架,可以实现复杂的定时任务调度。在 JFinal 框架中使用 Quartz 可以通过以下步骤实现: 1. 引入 Quartz 依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> </dependency> ``` 2. 编写定时任务类 ```java public class MyJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("Hello World!"); } } ``` 3. 配置定时任务JFinal配置文件中添加以下代码: ```java public class DemoConfig extends JFinalConfig { public void configConstant(Constants me) { // ... } public void configRoute(Routes me) { // ... } public void configPlugin(Plugins me) { // ... } public void configInterceptor(Interceptors me) { // ... } public void configHandler(Handlers me) { // ... } public void afterJFinalStart() { try { // 创建 Scheduler SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); // 创建 JobDetail JobDetail job = JobBuilder.newJob(MyJob.class) .withIdentity("myJob", "group1") .build(); // 创建 Trigger Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("myTrigger", "group1") .startNow() .withSchedule(simpleSchedule() .withIntervalInSeconds(10) .repeatForever()) .build(); // 将 JobDetail 和 Trigger 添加到 Scheduler 中 sched.scheduleJob(job, trigger); // 启动 Scheduler sched.start(); } catch (SchedulerException e) { e.printStackTrace(); } } } ``` 以上代码会在 JFinal 启动后创建一个定时任务,每隔 10 秒钟打印一次 "Hello World!"。 2. 使用ScheduledExecutorService定时任务 ScheduledExecutorService 是 Java 提供的一个定时任务调度器,可以很方便地实现简单的定时任务。在 JFinal 框架中使用 ScheduledExecutorService 可以通过以下步骤实现: 1. 编写定时任务类 ```java public class MyTask implements Runnable { public void run() { System.out.println("Hello World!"); } } ``` 2. 配置定时任务JFinal配置文件中添加以下代码: ```java public class DemoConfig extends JFinalConfig { public void configConstant(Constants me) { // ... } public void configRoute(Routes me) { // ... } public void configPlugin(Plugins me) { // ... } public void configInterceptor(Interceptors me) { // ... } public void configHandler(Handlers me) { // ... } public void afterJFinalStart() { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(new MyTask(), 0, 10, TimeUnit.SECONDS); } } ``` 以上代码会在 JFinal 启动后创建一个定时任务,每隔 10 秒钟打印一次 "Hello World!"。 注意事项: 1. 定时任务需要在 JFinal 启动后创建,因此需要在 afterJFinalStart() 方法中配置定时任务。 2. 如果使用 Quartz 定时任务,需要在 JFinal 启动前初始化 Quartz,否则会出现 "Scheduler is not started" 的错误。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值