com.janeluo.jfinalplus.plugin.cron.Cron4jPlugin Maven / Gradle / Ivy
/**
* Copyright (c) 2011-2013, kidzhou 周磊 ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.janeluo.jfinalplus.plugin.cron;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.janeluo.jfinalplus.kit.Reflect;
import com.janeluo.jfinalplus.kit.ResourceKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.IPlugin;
import it.sauronsoftware.cron4j.Scheduler;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* 轻量级定时任务插件
*
*/
public class Cron4jPlugin implements IPlugin {
private static final String JOB = "job";
private final Log log = Log.getLog(getClass());
private Map jobs = Maps.newLinkedHashMap();
private String config;
private Scheduler scheduler;
private Map jobProp;
public Cron4jPlugin add(String jobCronExp, Runnable job) {
jobs.put(job, jobCronExp);
return this;
}
public Cron4jPlugin config(String config) {
this.config = config;
return this;
}
@Override
public boolean start() {
loadJobsFromProperties();
startJobs();
return true;
}
private void startJobs() {
scheduler = new Scheduler();
Set> set = jobs.entrySet();
for (Entry entry : set) {
scheduler.schedule(entry.getValue(), entry.getKey());
log.debug(entry.getValue() + " has been scheduled to run and repeat based on expression: " + entry.getKey());
}
scheduler.start();
}
private void loadJobsFromProperties() {
if (StrKit.isBlank(config)) {
return;
}
jobProp = ResourceKit.readProperties(config);
Set> entries = jobProp.entrySet();
for (Entry entry : entries) {
String key = entry.getKey();
if (!key.endsWith(JOB) || !isEnableJob(enable(key))) {
continue;
}
String jobClassName = jobProp.get(key) + "";
String jobCronExp = jobProp.get(cronKey(key)) + "";
Class clazz = Reflect.on(jobClassName).get();
try {
jobs.put(clazz.newInstance(), jobCronExp);
} catch (Exception e) {
Throwables.propagate(e);
}
}
}
private String enable(String key) {
return key.substring(0, key.lastIndexOf(JOB)) + "enable";
}
private String cronKey(String key) {
return key.substring(0, key.lastIndexOf(JOB)) + "cron";
}
private boolean isEnableJob(String enableKey) {
Object enable = jobProp.get(enableKey);
return enable != null && "true".equalsIgnoreCase((enable + "").trim());
}
@Override
public boolean stop() {
scheduler.stop();
return true;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy