Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding CronRunner #5

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>org.midgardarmy</groupId>
<artifactId>bifrost</artifactId>
<version>0.0.1-SNAPSHOT</version>
<version>1.2.0-SNAPSHOT</version>

<properties>
<logback.version>1.2.3</logback.version>
Expand Down Expand Up @@ -111,7 +111,19 @@
<dependency>
<groupId>com.cronutils</groupId>
<artifactId>cron-utils</artifactId>
<version>7.0.0</version>
<version>7.0.4</version>
</dependency>

<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>

<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>

<dependency>
Expand Down
7 changes: 7 additions & 0 deletions src/main/java/net/zerofill/MainRunner.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package net.zerofill;

import net.zerofill.cronrunner.CronRunner;
import net.zerofill.utils.BotUtils;
import net.zerofill.utils.ConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sx.blah.discord.api.IDiscordClient;

import net.zerofill.utils.DataUtils;
Expand All @@ -11,6 +14,8 @@

public class MainRunner {

private static final Logger logger = LoggerFactory.getLogger(MainRunner.class);

public static void main(String[] args){
String token;
if(args.length != 1){
Expand Down Expand Up @@ -42,6 +47,8 @@ public static void main(String[] args){
});

client.login();
CronRunner cr = new CronRunner();
cr.run();
}

}
98 changes: 98 additions & 0 deletions src/main/java/net/zerofill/cronrunner/CronRunner.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package net.zerofill.cronrunner;

import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;

import net.zerofill.cronrunner.jobs.Reminder;
import net.zerofill.utils.ConfigUtils;
import net.zerofill.utils.DataUtils;
import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.ScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.spi.MutableTrigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.cronutils.model.CronType.QUARTZ;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

public class CronRunner {

private static final Logger logger = LoggerFactory.getLogger(CronRunner.class);

private static List<Map<String, Object>> events = DataUtils.getEvents();

private static List<String> remindList = ConfigUtils.getList("reminder.ids");
private static String remindBefore = ConfigUtils.getString("reminder.before");

private static CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));

public void run() {
try {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();

for (Map<String, Object> event : events) {
if (remindList.contains(event.get("id").toString())) {

ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(event.get("schedule").toString()));
ZonedDateTime now = ZonedDateTime.now();
Optional<ZonedDateTime> nextTime = executionTime.nextExecution(now);
Date execution = null;

if (nextTime.isPresent()) {
execution = Date.from(nextTime.get().toInstant());
}

JobDetail job = newJob(Reminder.class).withIdentity(event.get("name").toString(), String.format("%s", event.get("id").toString())).build();
Trigger trigger = newTrigger().withIdentity("trigger", String.format("event%s", event.get("id").toString()))
.startAt(execution).build();

Date ft = scheduler.scheduleJob(job, trigger);
logger.info(String.format("%s has been scheduled to run at: %s and repeat based on expression: %s", job.getKey(), ft, trigger.getStartTime()));
}
}

scheduler.start();
addShutdownHook(scheduler);

} catch (SchedulerException se) {
logger.error(se.getLocalizedMessage());
}
}

private void addShutdownHook(Scheduler scheduler) {
Thread t = new Thread("Quartz Shutdown-Hook") {
@Override public void run() {
logger.info("Shutting down Quartz...");
try {
scheduler.shutdown();
} catch (SchedulerException e) {
logger.info(
"Error shutting down Quartz: " + e.getMessage(), e);
}
}
};
Runtime.getRuntime().addShutdownHook(t);
}

public CronRunner() {}
}
18 changes: 18 additions & 0 deletions src/main/java/net/zerofill/cronrunner/jobs/Reminder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package net.zerofill.cronrunner.jobs;

import net.zerofill.utils.BotUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Reminder implements Job {

private static final Logger logger = LoggerFactory.getLogger(Reminder.class);

public void execute(JobExecutionContext context) {
}

public Reminder() {}
}
1 change: 0 additions & 1 deletion src/main/java/net/zerofill/roster/Roster.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ protected static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT
try (InputStreamReader isr = new InputStreamReader(in)) {
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, isr);


// Build flow and trigger user authorization request.
flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
Expand Down
9 changes: 9 additions & 0 deletions src/main/java/net/zerofill/utils/ConfigUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
Expand Down Expand Up @@ -43,6 +45,13 @@ public static String getString(String key) {
return ConfigUtils.properties.getProperty(key);
}

public static List<String> getList(String key) {
if (ConfigUtils.properties.isEmpty()) {
init();
}
return Arrays.asList(ConfigUtils.properties.getProperty(key).split(","));
}

public static int getInt(String key) {
if (ConfigUtils.properties.isEmpty()) {
init();
Expand Down
45 changes: 24 additions & 21 deletions src/main/java/net/zerofill/utils/DataUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,15 @@ public static Map<Integer, Map<String, Object>> getItemsByIDs(List<Integer> ids)
for (int i = 0; i < ids.size(); i++) {
selectPreparedStatement.setInt(i + 1, ids.get(i));
}
ResultSet rs = selectPreparedStatement.executeQuery();
while (rs.next()) {
Map<String, Object> result = new HashMap<>();
result.put("id", rs.getInt("id"));
result.put("name", rs.getString("name_japanese"));
result.put("aegisName", rs.getString("name_english"));
result.put("slots", rs.getInt("slots"));
results.put(rs.getInt("id"), result);
try (ResultSet rs = selectPreparedStatement.executeQuery()) {
while (rs.next()) {
Map<String, Object> result = new HashMap<>();
result.put("id", rs.getInt("id"));
result.put("name", rs.getString("name_japanese"));
result.put("aegisName", rs.getString("name_english"));
result.put("slots", rs.getInt("slots"));
results.put(rs.getInt("id"), result);
}
}
} catch (SQLException e) {
if (logger.isDebugEnabled()) {
Expand All @@ -145,9 +146,10 @@ public static List<Integer> getMobIDsByName(String name) {
selectPreparedStatement.setString(1, String.format("%%%s%%", name.toLowerCase()));
selectPreparedStatement.setString(2, String.format("%%%s%%", name.toLowerCase()));

ResultSet rs = selectPreparedStatement.executeQuery();
while (rs.next()) {
results.add(rs.getInt("ID"));
try (ResultSet rs = selectPreparedStatement.executeQuery()) {
while (rs.next()) {
results.add(rs.getInt("ID"));
}
}
} catch (SQLException e) {
if (logger.isDebugEnabled()) {
Expand All @@ -171,16 +173,17 @@ public static List<Map<String, Object>> getEvents() {

try {
selectPreparedStatement = conn.prepareStatement(selectQuery.toString());
ResultSet rs = selectPreparedStatement.executeQuery();
while (rs.next()) {
Map<String, Object> result = new HashMap<>();
result.put("id", rs.getInt("id"));
result.put("name", rs.getString("name"));
result.put("schedule", rs.getString("schedule"));
result.put("start", rs.getTimestamp("start"));
result.put("end", rs.getTimestamp("end"));
result.put("duration", rs.getLong("duration"));
results.add(result);
try (ResultSet rs = selectPreparedStatement.executeQuery()) {
while (rs.next()) {
Map<String, Object> result = new HashMap<>();
result.put("id", rs.getInt("id"));
result.put("name", rs.getString("name"));
result.put("schedule", rs.getString("schedule"));
result.put("start", rs.getTimestamp("start"));
result.put("end", rs.getTimestamp("end"));
result.put("duration", rs.getLong("duration"));
results.add(result);
}
}
} catch (SQLException e) {
if (logger.isDebugEnabled()) {
Expand Down
15 changes: 14 additions & 1 deletion src/main/resources/application.properties.example
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,17 @@ shivtr.pass=
# Bifrost Config #
##################
bifrost.python=
bifrost.mvpbot.location=
bifrost.mvpbot.location=

###################
# Reminder Config #
###################
reminder.ids=
reminder.before=

####################
# Quartz Scheduler #
####################
org.quartz.scheduler.instanceName=MyScheduler
org.quartz.threadPool.threadCount=3
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore