I used Jobschuler for sending notification every x minutes(determined dynamically) like this
ComponentName componentName = new ComponentName(context,ClsJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, componentName)
.setPeriodic(duration * 60 * 1000); //setting in millisecond
JobScheduler jobScheduler = (JobScheduler) context.getSystemService (Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(builder.build());
and its working great it sends notification on time defined in JobService
now how can I convert it into firebase job scheduler, I did like this
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job job = dispatcher.newJobBuilder()
.setService(ClsJobService.class)
.setTag("notification") // uniquely identifies the job
.setTrigger(Trigger.executionWindow(0, duration * 60))
.setLifetime(Lifetime.FOREVER)
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.setRecurring(true)
.build();
dispatcher.mustSchedule(job);
but I sends notification only once when schedules, and after that not
My best guess is that you should change setTrigger() to:
.setTrigger(Trigger.executionWindow(duration * 60, duration * 60))
EDITED to fix executionWindow
Related
I need help in externalizing the below cron schedule or executing it dynamically. For example, in the below code it is hardcoded to perform every Saturday: cronSchedule("0 0 12 ? * SAT"). I want the value inside the cronSchedule() to externalize so that even after the server is started, I can still change the cron schedule to Monday or every day based on my choice and it can be run. I am looking for suggestion in java and not in spring.
public void run() throws Exception {
// Getting a reference to a scheduler
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
// job will run every week at Saturday 12 Noon Server Time
JobDetail job = newJob(CachingJob.class).withIdentity("job1", "group1").build();
CronTrigger trigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0 0 12 ? * SAT"))
.build();
Date ft = sched.scheduleJob(job, trigger);
sched.start();
SchedulerMetaData metaData = sched.getMetaData();
}
Any input or suggestion is appreciated.
We can perform below method to reschedule the job :
cronScheduler.rescheduleJob(cronTrigger.getKey(), newTrigger().withIdentity("customTrigger", "defaultGroup")
.withSchedule(cronSchedule(cronExpression)).build());
i have created job with like creating with one jobName and different keys(see JobDataMap)
CronTriggerImpl trigger = new CronTriggerImpl();
JobDetailImpl jobDetail = null;
trigger.setMisfireInstruction(CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING);
trigger.setName(getUniqueJobId());
trigger.setCronExpression(cronExpression);
trigger.setTimeZone(timeZone);
JobDataMap dataMap = new JobDataMap();
dataMap.put("jobName", "job");
dataMap.put("id", "key");
trigger.setJobDataMap(jobDataMap);
jobDetail = new JobDetailImpl();
jobDetail.setName(getUniqueJobId());
jobDetail.setJobDataMap(jobDataMap);
jobDetail.setJobClass(JobLauncherDetails.class);
scheduler.scheduleJob(jobDetail, trigger);
it is working properly but i want to delete the specific trigger how can i delete
i had seen fee source but those are not matching. please help me out
**Updated : **
i want to delete like
schedule.deleteJob(JobKey) what will be the job key as per my schedule configuration
or should i use schedule.unScheduler()
org.quartz.Scheduler#unscheduleJob accepts the trigger key as parameter. Hence, you can remove the trigger specified, not the job.
public static boolean removeJob(String jobName, String jobGroup) throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
if (scheduler.checkExists(triggerKey)) {
scheduler.unscheduleJob(triggerKey); // trigger + job
}
logger.info(">>>>>>>>>>> removeJob success, triggerKey:{}", triggerKey);
return true;
}
Hope that helps.
UPDATE:
We don't know actually your functional need. But, you can create Trigger in cleaner way and bind it to a given Job:
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger3", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("0 0/2 8-17 * * ?"))
.forJob("myJob", "group1") // Binding the Trigger to the Job
.build();
I see you are using JobDataMap in your Trigger. This is useful for passing parameters to a Job that are specific to the executions of the trigger. Do you need really that?
Useful link: https://www.baeldung.com/quartz
I want it fire a job once on every 1st day in a every month that should be any week day.But if it is sunday on 1st do not fire the job just postpone it to fire at 2nd day and immediately terminate schedule.
Again do the same process of scheduling for next months also.?
Below is the code to schedule it for every 55 seconds for testing envrironment and how about the destroy method?
QuartzPlugin.java
public class QuartzPlugin implements PlugIn {
#Override
public void destroy() {
}
#Override
public void init(ActionServlet servlet, ModuleConfig config) throws ServletException {
// define the job and tie it to our MyJob class
JobDetail job = JobBuilder.newJob(SchedulerJob.class).withIdentity("anyJobName", "group1").build();
try {
// Cron Trigger the job to run now, and then repeat every 55 secs
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("anyTriggerName", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("0/55 * * * * ?"))
//Every 1 minute "0 0/1 * 1/1 * ? *"
// Every 55 Sec "0/55 * * * * ?"
// Every 5 Sec "0/5 * * * * ?"
// Every month 1st day "0 10 1-7 * *"
.build();
// Grab the Scheduler instance from the Factory
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
// and start it off
scheduler.start();
// Tell quartz to schedule the job using our trigger
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
SchedularJob.java
public class SchedulerJob implements Job {
private ArrayList mapList = new ArrayList();
private DAO dao = new DAO();
private HSSFWorkbook workbook = new HSSFWorkbook();
private FileOutputStream fileOut = null;
public void execute(JobExecutionContext context) throws JobExecutionException {
String dirpath = System.getProperty("user.dir").replaceAll("bin", "") + "webapps/it_email/sent/email_"
+ new SimpleDateFormat("dd-MM-yyyy").format(new Date());
String genStatus = generateExcel(dirpath);
System.out.println("genStatus::" + genStatus);
if (genStatus.equals("Y")) {
String text = "Please find attached case list dated "
+ new SimpleDateFormat("dd-MM-yyyy").format(new Date()) + "."
+ "\n\n Microsoft Excel is required to open this attachment.\n\n"
+ "Registrar Judicial,High Court of Judicature at Hyderabad.\n\n"
+ "This email is System generated. Please do not reply to this email ID.\n\n "
+ "Disclaimer:The NIC/High Court is not responsible for non-delivery of emails.";
String subject = "HIGH COURT:Availability of Case Data.";
String to = "ajaythakur2014#gmail.com";
String filetype = ".xls";
sendEmail(to, subject, text, dirpath, filetype);
System.out.println("For every 55 secs");
}
}
When the above code is run i sporadically get the
Oracle 9i Production Environment : IO Exception : The Network Adapter could not establish the connection
i guess creating more no of new connections every 55 seconds.
Could be useful this link ,where there is the official documentation :MonthlyTrigger
I want to fetch the Cloudmetrics data for my EC2 instance so that I can draw graphs using those data and display it on my android device. How do I do that? Is there any sample program or tutorial for the same?
Thanks in advance.
This is what I am doing:
private static void findCloudWatchData() {
AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(new BasicAWSCredentials(AccessKey, SecretKey));
cloudWatch.setEndpoint("monitoring.us-east-1.amazonaws.com");
long offsetInMilliseconds = 1000 * 60 * 60 * 24;
Dimension instanceDimension = new Dimension();
instanceDimension.setName("instanceid");
instanceDimension.setValue(instanceid);
GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
.withStartTime(new Date(new Date().getTime() - offsetInMilliseconds))
.withNamespace("AWS/EC2")
.withPeriod(60 * 60)
.withMetricName("CPUUtilization")
.withStatistics("Average")
.withDimensions(Arrays.asList(instanceDimension))
.withEndTime(new Date());
GetMetricStatisticsResult getMetricStatisticsResult = cloudWatch.getMetricStatistics(request);
}
As you have tagged your question with android I assume that you want to fetch CloudWatch-Metrics for your EC2 Instances in an Android-App.
So this might be a good starting point for you:
Getting Started with the AWS SDK for Android .
You need to:
download AWS SDK for Android
create your access keys for AWS (via IAM)
read the documentation for aws-android-sdk-VERSION-cloudwatch.jar
start using the fetched data from CloudWatch
Regards
Tom
I suppose you are struck only with reading the data and plotting the graph.
private static void findCloudWatchData() {
LinkedHashMap<Date,Double> map=new HashMap<Date,Double>();
AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(new BasicAWSCredentials(AccessKey, SecretKey));
cloudWatch.setEndpoint("monitoring.us-east-1.amazonaws.com");
long offsetInMilliseconds = 1000 * 60 * 60 * 24;
Dimension instanceDimension = new Dimension();
instanceDimension.setName("instanceid");
instanceDimension.setValue(instanceid);
GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
.withStartTime(new Date(new Date().getTime() - offsetInMilliseconds))
.withNamespace("AWS/EC2")
.withPeriod(60 * 60)
.withMetricName("CPUUtilization")
.withStatistics("Average")
.withDimensions(Arrays.asList(instanceDimension))
.withEndTime(new Date());
GetMetricStatisticsResult getMetricStatisticsResult = cloudWatch.getMetricStatistics(request);
}
//To read the Data
for (Datapoint dp : result.getDatapoints()) {
map.put(dp.getTimeStamp(), dp.getAverage()); //or getMaximum() or whatever Statistics you are interested in. You can also maintain a list of the statistics you are interested in. Ex: request.setStatistics(list)
}
Note that the datapoints are NOT in order. Sort the HashMap and plot the graph.
I found that AWS/Billing metrics "live" only in one region - us-east-1.
Also, AWS CLI (aws cloudwatch get-metric-statistics) will errorr out if you try to grab more than 1440 data points from CloudWatch.
If you encounter it set larger --period.
Similar to what you are trying to achieve using Java on Android I wrote EC2_Metrics_Plotter for OS Windows using Python/matplotlib.
Working with Java Quartz, I was able to schedule one job. Then I tried something like the following code to be able to add an other job. Now neither seems to trigger at the defined time. What am I doing wrong?
I want to use approach like following, not xml configuration.
scheduler = StdSchedulerFactory.getDefaultScheduler();
JobDetail jobFull = new JobDetail("job1", "group1", IntegrationJobFull.class);
JobDetail jobPartial = new JobDetail("job2", "group1", IntegrationJobPartial.class);
CronTrigger triggerFull = new CronTrigger("trigger1", "group1", "job1", "group1", "0 15 3 * * ?");
CronTrigger triggerPartial = new CronTrigger("trigger2", "group1", "job2", "group1", "* 0,30 * * * ?");
scheduler.addJob(jobFull, false);
scheduler.addJob(jobPartial, false);
scheduler.scheduleJob(triggerFull);
scheduler.scheduleJob(triggerPartial);
scheduler.start();
The JobDetails created above are non-durable, this means that the addJob method will fail. Use the overloaded scheduleJob method to associate the job and the trigger.
Remove the addJob and scheduleJob calls and replace with:
scheduler.scheduleJob(jobFull, triggerFull);
scheduler.scheduleJob(jobPartial, triggerPartial);
Also * has been specifed the seconds field for trigger2. This will mean that the job will be triggered every second for the specified minutes. I'm not sure if that was the intention.
The desired cron expression may be:
"0 0,30 * * * ?"