Execute a job every N weeks between X and Y hour - triggers

I am using Quartz.NET library and I need to execute a job every two days and repeat it every two hours between 22 PM and 6 AM. I don't know how to achieve this. I tried all of triggers combining them with calendars to exclude other hours, but nothing works as I want. Any idea?

This is the answer.
protected void Application_Start()
{
//....
EveryTwoWeek();
//....
}
private void MainJob()
{
int hourNumber = 2;
var schedFact = new Quartz.Impl.StdSchedulerFactory();
var sched = schedFact.GetScheduler();
sched.Start();
var twoHourlyTriggerFrom22To6 = Quartz.TriggerUtils.MakeHourlyTrigger(hourNumber);
twoHourlyTriggerFrom22To6.StartTimeUtc = System.DateTime.Now.Date.AddHours(22);
twoHourlyTriggerFrom22To6.EndTimeUtc = System.DateTime.Now.Date.AddHours(22 + 8);
var jobDetail = new Quartz.JobDetail("Method", methodType);
sched.ScheduleJob(jobDetail, twoHourlyTriggerFrom22To6);
}
private void EveryTwoDays()
{
int dayNumber = 2;
var schedFact = new Quartz.Impl.StdSchedulerFactory();
var sched = schedFact.GetScheduler();
sched.Start();
var everyTwoDaysTrigger = Quartz.TriggerUtils.MakeImmediateTrigger(int.MaxValue, new System.TimeSpan(0, dayNumber * 24, 0, 0));
everyTwoDaysTrigger.StartTimeUtc = System.DateTime.Now.Date;
var jobDetail = new Quartz.JobDetail("MainJob", mainJobType);
sched.ScheduleJob(jobDetail, everyTwoDaysTrigger);
}

What about 0 0 0,2,4,6,22 1/2 * ? *
Strictly speaking, this isn't every two days, but on the 1st, 3rd, 5th etc of each month.

Related

Is there any way to get upload image remaing time using dio?

I am uploading image using Dio. I got the upload progress in percentage but I also want
to get the upload reaming time.
onSendProgress: (int sent, int total) {
uploadProgress.value = "${(sent / total * 100).toStringAsFixed (0)}%";
},
Is there any way to get the reaming time ?
Convert the remaining file size to megabytes.
Convert upload speed to megabytes.
file size / (uploads per second / 8 )
ex) 200M/(10M/8) = 160 seconds
I simulated an upload environment, I believe you can apply it to the Dio environment, good luck.
void test() {
var totalSize = 120000.0;
var uploadSpeed = 0.0;
var timeLeft = 0.0;
var startTime = DateTime.now();
var curTime = DateTime.now();
Timer? timer;
timer = Timer.periodic(Duration(seconds: 1), (t) {
if (t.tick > 9) timer?.cancel();
curTime = DateTime.now();
var currentSize = 1500。0;
var usedTime =
((curTime.difference(startTime).inMilliseconds) / 1000).toInt();
uploadSpeed = (totalSize / usedTime) / 1024;
totalSize = totalSize - currentSize;
timeLeft = totalSize / (currentSize / 8);
print('useTime : $usedTime');
print('uploadSpeed : $uploadSpeed');
print('File Size : $totalSize');
print('uploadSpeed :$uploadSpeed');
print('timeLeft $timeLeft');
});
}

How to store System.currentTimeMillis() in an array with a park time simulator

I'm trying to store the time in milliseconds for every time this time park is executed. And then I would like to use HdrHistogram to represent the latency.
However, i can't store the times in my array. Please, could you provide any help?
public class PracticeLatency1
{
public static void main(String [] args)
{
int[] startTimes;
long startTime;
int index=0;
startTimes = new int[10000];
startTime = System.currentTimeMillis();
runCalculations();
startTimes[index++] = (int) (System.currentTimeMillis() - startTime);
System.out.println(startTimes);
}
/**
* Run the practice calculations
*/
// System.currentTimeMillis()
private static void runCalculations()
{
// Create a random park time simulator
BaseSyncOpSimulator syncOpSimulator = new SyncOpSimulRndPark(TimeUnit.NANOSECONDS.toNanos(100),
TimeUnit.MICROSECONDS.toNanos(100));
// Execute the operation lot of times
for(int i = 0; i < 10000; i++)
{
syncOpSimulator.executeOp();
}
// TODO Show the percentile distribution of the latency calculation of each executeOp call
}
}

How to convert seconds to minutes in Dart?

I'm learning Dart & flutter for 2 days and I'm confused about how to convert seconds (for example 1500sec) to minutes.
For studying the new language, I'm making Pomodoro timer, and for test purposes, I want to convert seconds to MM: SS format. So far, I got this code below, but I'm stuck for a couple of hours now... I googled it but could not solve this problem, so I used Stackoverflow. How should I fix the code?
int timeLeftInSec = 1500;
void startOrStop() {
timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
if (timeLeftInSec > 0) {
timeLeftInSec--;
timeLeft = Duration(minutes: ???, seconds: ???)
} else {
timer.cancel();
}
}
}
}
This code works for me
formatedTime({required int timeInSecond}) {
int sec = time % 60;
int min = (time / 60).floor();
String minute = min.toString().length <= 1 ? "0$min" : "$min";
String second = sec.toString().length <= 1 ? "0$sec" : "$sec";
return "$minute : $second";
}
now just call the function
formatedTime(timeInSecond: 152)
formated time example
Without formatting:
int mins = Duration(seconds: 120).inMinutes; // 2 mins
Formatting:
String formatTime(int seconds) {
return '${(Duration(seconds: seconds))}'.split('.')[0].padLeft(8, '0');
}
void main() {
String time = formatTime(3700); // 01:01:11
}
You can try this :
int minutes = (seconds / 60).truncate();
String minutesStr = (minutes % 60).toString().padLeft(2, '0');
This is the way I've achieved desired format of MM:SS
Duration(seconds: _secondsLeft--).toString().substring(2, 7);
Here is an example of what toString method returns:
d = Duration(days: 0, hours: 1, minutes: 10, microseconds: 500);
d.toString(); // "1:10:00.000500"
So with the substring method chained you can easily achive more formats e.g. HH:MM:SS etc.
Check out this piece of code for a count down timer with formatted output
import 'dart:async';
void main(){
late Timer timer;
int startSeconds = 120; //time limit
String timeToShow = "";
timer = Timer.periodic(Duration(seconds:1 ),(time){
startSeconds = startSeconds-1;
if(startSeconds ==0){
timer.cancel();
}
int minutes = (startSeconds/60).toInt();
int seconds = (startSeconds%60);
timeToShow = minutes.toString().padLeft(2,"0")+"."+seconds.toString().padLeft(2,"0");
print(timeToShow);
});
}
/*output
01.59
01.58
01.57
...
...
...
00.02
00.01
00.00*/
static int timePassedFromNow(String? dateTo) {
if (dateTo != null) {
DateTime targetDateTime = DateTime.parse(dateTo);
DateTime dateTimeNow = DateTime.now();
if (targetDateTime.isAfter(dateTimeNow)) {
Duration differenceInMinutes = dateTimeNow.difference(targetDateTime);
return differenceInMinutes.inSeconds;
}
}
return 0;
}
static String timeLeft(int seconds) {
int diff = seconds;
int days = diff ~/ (24 * 60 * 60);
diff -= days * (24 * 60 * 60);
int hours = diff ~/ (60 * 60);
diff -= hours * (60 * 60);
int minutes = diff ~/ (60);
diff -= minutes * (60);
String result = "${twoDigitNumber(days)}:${twoDigitNumber(hours)}:${twoDigitNumber(minutes)}";
return result;
}
static String twoDigitNumber(int? dateTimeNumber) {
if (dateTimeNumber == null) return "0";
return (dateTimeNumber < 9 ? "0$dateTimeNumber" : dateTimeNumber).toString();
}

ADO.NET: How can we update a DataTable column values as fast as calculated columns does?

I have a small test program that creates a DataTable with 1M rows.
Then I add a calculated column (Expression column), it's super fast like a second.
Then I just try to add a new column and set values to it, it takes more than 10 seconds.
DataTable update is slow. How can I make it as fast as calculated column?
10 seconds does seem acceptable but that is just a test program to show the difference.
This can become worst depending on how many rows, columns, etc.
Anyway if calculated column is able to do it that fast, hopefully we can get same performance with normal updates.
It seems calculated columns is able to turn off some notifications or other things. I'm not sure.
Any idea? Advice? Maybe I'm missing something when updating the DataTable.
Thanks in advance
Below is the code sample I'm using:
using System;
using System.Data;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
try
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
Console.WriteLine("DataTable creation started ...");
DataTable data = new DataTable();
int nbrCols = 50;
for (int i = 0; i < nbrCols; i++)
{
data.Columns.Add(string.Concat("COL_", (i + 1)), typeof(double));
}
System.Random r = new System.Random();
data.BeginLoadData();
int nbrows = 1000000;
for (int i = 0; i < nbrows; i++)
{
DataRow newRow = data.NewRow();
for (int j = 0; j < nbrCols; j++)
{
newRow[j] = r.NextDouble();
}
data.Rows.Add(newRow);
}
data.EndLoadData();
watch.Stop();
Console.WriteLine("DataTable creation = " + watch.ElapsedMilliseconds / 1000.0);
int colIndexFlow1 = data.Columns.IndexOf("COL_1");
int colIndexFlow2 = data.Columns.IndexOf("COL_2");
/* Add a calculated columns */
watch.Restart();
data.Columns.Add("CALC_1", typeof(double), "COL_1 + COL_2");
data.AcceptChanges();
watch.Stop();
Console.WriteLine("Calculated Column creation = " + watch.ElapsedMilliseconds / 1000.0);
/* Add a new column */
watch.Restart();
data.BeginLoadData();
data.Columns.Add("NEW_1", typeof(double));
int colIdx = data.Columns.IndexOf("NEW_1");
foreach (DataRow row in data.Rows)
{
//double val = row.Field<double>("COL_1") + row.Field<double>("COL_2");
//row.SetField<double>(colIdx, val);
// Most of the time is spent to actually set the data
// Question is how can we make the update happening as fast as the update done when using a calculated column.
row.SetField<double>(colIdx, 2.0);
}
data.AcceptChanges();
data.EndLoadData();
watch.Stop();
Console.WriteLine("New Column creation = " + watch.ElapsedMilliseconds / 1000.0);
}
catch (Exception ex)
{
Console.WriteLine("Error=" + ex.Message);
}
finally
{
Console.ReadLine();
Console.WriteLine("Press any key to exit");
}
}
}
}

How to calculate ages correctly in GWT?

This is what I did, but it did not take into account the leap years
public static int calculateAge(String yyyyMMddBirthDate){
DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd");
Date birthDateDate = fmt.parse(yyyyMMddBirthDate);
Date nowDate=new Date();
long differenceInMillis=nowDate.getTime()-birthDateDate.getTime();
int days=(int)Math.abs(differenceInMillis/(1000*60*60*24));
int ages=(int)days/365;
System.out.println(days+" days");
return ages;
}
I heard we have to use Joda time to calculate ages, but seem GWT does not support Joda time.
Can we just simply use simple code to calculate ages in GWT rather than using library?
Note: This is GWT question, not Java one. The GWT does not support java.text or Joda.
This should work (even for GWT), at least for births that are after about 1582:
// currentDate and birthDate are in the format yyyyMMdd
final int age = (Integer.valueOf(currentDate) - Integer.valueOf(birthDate)) / 10000;
You've already calculated the age in milliseconds, but you need to convert it to the highly arbitrary Western "years."
Best to use a library like JodaTime or Calendar that have these edge cases programmed in. Luckily people have ported it to GWT.
See: Date time library for gwt
Update: It really depends on what answer you want. Generally, comparing the current year to the birth year would get you the correct answer. So, if you want integer years lived so far:
Date dateBirth = ...;
Date dateNow = new Date();
int yearsOld = dateNow.getYear() - dateBirth.getYear();
To account for the fractional year, you'll need to test for leap days (if you want day precision) or leap seconds (if you want leap second precision). So, again, it depends what result you seek, which you've not said.
Regardless, this has nothing to do with GWT and everything to do with the basics of date/time math. either you'll have to bring it in via a library, or do it yourself. I'd suggest a library, since the calculations are elaborate. Just look inside the BaseCalendar that Java uses.
I ran into this today and here's what I came up with. This models how I would mentally calculate someone's age given a date of birth.
(using com.google.gwt.i18n.shared.DateTimeFormat)
private int getAge(Date birthDate) {
int birthYear = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(birthDate));
int birthMonth = Integer.parseInt(DateTimeFormat.getFormat("MM").format(birthDate));
int birthDayOfMonth = Integer.parseInt(DateTimeFormat.getFormat("dd").format(birthDate));
Date today = new Date();
int todayYear = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(today));
int todayMonth = Integer.parseInt(DateTimeFormat.getFormat("MM").format(today));
int todayDayOfMonth = Integer.parseInt(DateTimeFormat.getFormat("dd").format(today));
boolean hasHadBirthdayThisYear;
if (todayMonth < birthMonth) {
hasHadBirthdayThisYear = false;
} else if (todayMonth > birthMonth) {
hasHadBirthdayThisYear = true;
} else {
hasHadBirthdayThisYear = birthDayOfMonth <= todayDayOfMonth;
}
int age = todayYear - birthYear;
if (!hasHadBirthdayThisYear) {
age--;
}
return age;
}
import java.util.*;
public class Practice2 {
public static int calculateAge(String yyyyMMddBirthDate) {
// check the input ?
int birthYear = Integer.parseInt(yyyyMMddBirthDate.substring(0,4));
Date nowDate = new Date();
int nowYear = nowDate.getYear() + 1900;
//rough age and check whether need -- below
int roughAge = nowYear - birthYear;
int birthMonth = Integer.parseInt(yyyyMMddBirthDate.substring(5,7));
int birthDay = Integer.parseInt(yyyyMMddBirthDate.substring(8,10));
//1970-01-01T 00:00:00
long now = nowDate.getTime();
long days = now / (3600l * 1000l * 24l);
int daySum = 0;
for( int i = 1970; i < nowYear; i ++ ){
daySum = daySum + yearDays(i);
}
int[] monthDays = {31, 28 , 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
monthDays[1] = yearDays(nowYear) - 337;
for( int i = 0; i < birthMonth -1; i ++ ){
daySum = daySum + monthDays[i];
}
daySum = daySum + birthDay;
if( daySum > days ){
roughAge--;
}
return roughAge;
}
private static int yearDays(int year) {
if( ( (year%100==0)&&(year%400==0) )
||((year%100!=0)&&(year%4==0))){
return 366;
}
return 365;
}
public static void main(String[] args) {
System.out.println(calculateAge("1990-12-30"));
}
}