Cron Expression - Run every hour after a start time - quartz-scheduler

I want to run a cron job every hour after a certain start time. Currently my cron job expression is
cronExpression = seconds + " " + minutes + " " + hours +"/1" + " " + " * * ? *" ;
(seconds, minutes, hours are passed in by the user selection)
The job starts at the right time and runs every hour until midnight but then stops until the hour on the next day and then resumes. How do I get the job to continuously run and not stop at midnight?
I understand I can change the expression to
cronExpression = seconds + " " + minutes + " " * * * ? *" ;
but then it will not take into account the start time. It will just run at every hour.
Thanks in advance,
Rich

Do you mean you want the job to start at the given time and then run once hourly forever? If so, I don't think a cron expression is the right approach.
If you're using a scheduler it should be straightforward to start the job and run forever at a given interval. For example, here's a snippet from the Quartz scheduler docs for JobBuilder:
JobDetail job = newJob(MyJob.class)
.withIdentity("myJob")
.build();
Trigger trigger = newTrigger()
.withIdentity(triggerKey("myTrigger", "myTriggerGroup"))
.withSchedule(simpleSchedule()
.withIntervalInHours(1)
.repeatForever())
.startAt(futureDate(10, MINUTES))
.build();
scheduler.scheduleJob(job, trigger);

Run a wrapper every hour which runs your job if the current time is after your start time.
For example,
case $(date +%H) in
09 |1[0-6] ) pingcheck ;;
esac
would run pingcheck (whatever that is :-) between 09:00 and 16:59.

Use your own expression
cronExpression = seconds + " " + minutes + " " * * * ? *" ;
with the startAt(your start time) method() mentioning the start time of the trigger. This start time will implicitely tell the quartz when the trigger will start coming into effect.

Related

How can I enter and exit a trade at a given time?

I am trying to backtest a strategy in Tradingview on an hourly chart that goes short AUDJPY at 5am Japan time and exits with a market order at 7am on the same day. I am using the hour(time) function and the IANA timezone 'Asia/Tokyo'.
Below is the code. I verified that the variable hr picks up the right hour by plotting it in the chart. But when I run the Strategy Tester the result is "No Data" and no trades appear on the screen after I apply "Add to chart" to the script.
strategy("Foreign JPY", overlay=true, currency = currency.USD)
hr = hour(time, "Asia/Tokyo")
shortCondition = hr == 5
if (shortCondition)
strategy.entry("short", strategy.short, 100000)
exitCondition = hr == 7 and strategy.position_size < 0
if (exitCondition)
strategy.close("exit", 100000)
The exit condition in your example is executed only for entries with an "exit" id=. If you want to point to the existing short order, use its id= in the strategy.close() parameter:
if (exitCondition)
strategy.close("short", 100000)

Call to nonexistent function AHKv2

I am trying to create a simple InputBox pop-up that asks for an hour:minute combo, and then starts a countdown timer. When the timer reaches zero, it activates a window and then sends input into that window. I have followed the documentation and am still met with the same error over and over Call to nonexistent function. My script used to be far more complicated, but in an effort to troubleshoot, it has gotten progressively simpler and simpler ... and now it basically mirrors the documentation -- and yet, I still get this error. Fresh eyes on this would be greatly appreciated!
:*:obstimer::
;; Show the input box
USER_INPUT := InputBox("This is the prompt","This is the title",W200 H300 T30,"").value
;; Split the input time into hours and minutes
TimeArray := StrSplit(USER_INPUT, ":")
hours := TimeArray[1] ; Get the hours part
minutes := TimeArray[2] ; Get the minutes part
;; Convert the hours and minutes to seconds
loop_timer = (hours * 3600) + (minutes * 60)
;; Set a timer that will trigger the press_backtick function every 1000 milliseconds (1 second)
SetTimer, press_backtick, 1000
return
press_backtick:
loop_timer-- ; Decrement the loop timer by 1
if (loop_timer <= 0) { ; If the loop timer is less than or equal to 0
WinActivate, ahk_exe obs64.exe ; Activate the obs64.exe window
ControlSend, , {U+0060}, ahk_exe obs64.exe ; Send the backtick character ` to the obs64.exe window
SetTimer, press_backtick, off ; Turn off the timer
}
return
Your syntax is so far from being valid AHKv2 syntax, that the AHK script launcher deduces your script as being AHKv1, and therefore you get the error for a non existent function. (A function InputBox doesn't exist in AHKv1, it's a legacy command there)
Here's the script in AHKv2 syntax, there are loads of changes, and you also had some errors which wouldn't have worked even in v1.
I'd recommend you to go through v2 changes before trying to write v2 code (assuming you have a v1 background). Or if this is your first time writing AHK, be sure to look at v2 examples and documentations.
:*:obstimer::
{
global loop_timer
USER_INPUT := InputBox("This is the prompt", "This is the title", "W200 H300 T30", "").value
TimeArray := StrSplit(USER_INPUT, ":")
hours := TimeArray[1]
minutes := TimeArray[2]
loop_timer := (hours * 3600) + (minutes * 60)
SetTimer(press_backtick, 1000)
}
press_backtick()
{
global loop_timer
loop_timer-- ; Decrement the loop timer by 1
if (loop_timer <= 0) {
WinActivate("ahk_exe obs64.exe")
ControlSend("{U+0060}", , "ahk_exe obs64.exe")
SetTimer(press_backtick, 0)
}
}

Infinite loop stops

I have googled this a lot and I can only find answers that relate to conditions within the loop being met. I want this loop to run infinitely (Hence while 1==1) and I'm testing it at the moment by just leaving it running in Thonny. It runs for variable lengths of time and then just stops. It doesn't exit the program or stop running, it just behaves as if it's waiting for something but there's nothing that I can see that it's waiting for. The shell doesn't report any errors or report that it has stopped running, it simply stops printing the string in the fourth line print statement.
I am very new to python and Linux and I have no idea how to debug this problem or where to look for the stopping point. Even running it in debug mode doesn't render any helpful information. Has anyone got any suggestions please?
The only other thing that I have tried outside of what I have said is I have tried running it on a fresh install of Raspberry Pi OS on three different Raspberry Pi 4 Model B computers. It behaves exactly the same on all of them.
while 1==1:
time.sleep(1)
cnt = 1
print('One = One loop ' + str(datetime.today()) + ' CNT: ' + str(cnt))
while Decimal(target_temperature()) - Decimal(0.3) >= Decimal(actual_temperature()) and switch_state() == 'currently not running':
print('Before heating loop ' + str(datetime.today()))
try:
if cnt == 1:
if Decimal(target_temperature()) - Decimal(0.3) >= Decimal(actual_temperature()) and switch_state() == 'currently not running':
print('First heating loop ' + str(datetime.today()))
requests.get('http://192.168.1.167/4/on')
log_db('On', str(target_temperature()), str(actual_temperature()))
time.sleep(225)
requests.get('http://192.168.1.167/4/off')
log_db('Off', str(target_temperature()), str(actual_temperature()))
time.sleep(300)
cnt = cnt + 1
if(cnt != 1):
if Decimal(target_temperature()) - Decimal(0.3) >= Decimal(actual_temperature()) and switch_state() == 'currently not running':
print('Second heating loop ' + str(datetime.today()))
requests.get('http://192.168.1.167/4/on')
log_db('On', str(target_temperature()), str(actual_temperature()))
time.sleep(180)
requests.get('http://192.168.1.167/4/off')
log_db('Off', str(target_temperature()), str(actual_temperature()))
time.sleep(300)
except Exception as e:
print(e)
Bearing in mind i don't know anything about python i will try to help.
1 - The first thing i would do is put the whole program in a try catch block. That wasy if anything bad happens you should be told about it
try:
<all your code>
except Exception as e2:
print('The whole thing errored' + e2)
2 - The delays are in seconds? For testing i would change every sleep to (30) so you can see what is going on without getting too bored waiting, when you have it working then change the times back.
3 - I would add some more print('got here!') like where you have if(cnt == 1) add else print('first loop wasnt 1 it was ' + cnt)
4 - try and make the code easier for you to read, when it gets actually run it will be so optimized that it wont bear any relation to what you write. So write it in a way that is easiest for you
5 - You turn it on and then off, but if the off failed it would never be turned off, you should assume that it will go badly and that will be the day you get a big bill. Try and stop it if an error occurs by adding another check if actualTemp > targetTemp then turn it off?
6 - the http request might take ages, specify a time in seconds you are prepared to wait like , timeout=60
try:
while 1==1:
try:
time.sleep(30)
targetTemp = Decimal(target_temperature())
actualTemp = Decimal(actual_temperature())
switchState = switch_state()
print('Doing it at ' + str(datetime.now()) + ' target ' + str(targetTemp) + ' actual ' + str(actualTemp) + ' switch ' + switchState)
if targetTemp - Decimal(0.3) >= actualTemp and switchState == 'currently not running'
print('too cold turning it for a bit!')
requests.get('http://192.168.1.167/4/on', timeout=60)
log_db('On', targetTemp , actualTemp)
else if actualTemp > targetTemp and switchState != 'currently not running'
print('too hot turning it off!')
requests.get('http://192.168.1.167/4/off', timeout=60)
log_db('Off', targetTemp , actualTemp)
else
print('Not doing anything!')
except Exception as e1:
print('Loop errored -> ' + e1)
except Exception as e2:
print('Whole thing errored -> ' + e2)
Thanks Billy the Kid. You were right. Sometimes the devices that the loop uses via HTTPRequests just don't reapond (the two functions use HTTPRequests) and sometimes they create errors that aren't caught in the loop. Putting the whole thing in a try/catch oddly did identify that. Problem solved.

Twitter's Future.collect not working concurrently (Scala)

Coming from a node.js background, I am new to Scala and I tried using Twitter's Future.collect to perform some simple concurrent operations. But my code shows sequential behavior rather than concurrent behavior. What am I doing wrong?
Here's my code,
import com.twitter.util.Future
def waitForSeconds(seconds: Int, container:String): Future[String] = Future[String] {
Thread.sleep(seconds*1000)
println(container + ": done waiting for " + seconds + " seconds")
container + " :done waiting for " + seconds + " seconds"
}
def mainFunction:String = {
val allTasks = Future.collect(Seq(waitForSeconds(1, "All"), waitForSeconds(3, "All"), waitForSeconds(2, "All")))
val singleTask = waitForSeconds(1, "Single")
allTasks onSuccess { res =>
println("All tasks succeeded with result " + res)
}
singleTask onSuccess { res =>
println("Single task succeeded with result " + res)
}
"Function Complete"
}
println(mainFunction)
and this is the output I get,
All: done waiting for 1 seconds
All: done waiting for 3 seconds
All: done waiting for 2 seconds
Single: done waiting for 1 seconds
All tasks succeeded with result ArraySeq(All :done waiting for 1 seconds, All :done waiting for 3 seconds, All :done waiting for 2 seconds)
Single task succeeded with result Single :done waiting for 1 seconds
Function Complete
The output I expect is,
All: done waiting for 1 seconds
Single: done waiting for 1 seconds
All: done waiting for 2 seconds
All: done waiting for 3 seconds
All tasks succeeded with result ArraySeq(All :done waiting for 1 seconds, All :done waiting for 3 seconds, All :done waiting for 2 seconds)
Single task succeeded with result Single :done waiting for 1 seconds
Function Complete
Twitter's futures are more explicit about where computations are executed than the Scala standard library futures. In particular, Future.apply will capture exceptions safely (like s.c.Future), but it doesn't say anything about which thread the computation will run in. In your case the computations are running in the main thread, which is why you're seeing the results you're seeing.
This approach has several advantages over the standard library's future API. For one thing it keeps method signatures simpler, since there's not an implicit ExecutionContext that has to be passed around everywhere. More importantly it makes it easier to avoid context switches (here's a classic explanation by Brian Degenhardt). In this respect Twitter's Future is more like Scalaz's Task, and has essentially the same performance benefits (described for example in this blog post).
The downside of being more explicit about where computations run is that you have to be more explicit about where computations run. In your case you could write something like this:
import com.twitter.util.{ Future, FuturePool }
val pool = FuturePool.unboundedPool
def waitForSeconds(seconds: Int, container:String): Future[String] = pool {
Thread.sleep(seconds*1000)
println(container + ": done waiting for " + seconds + " seconds")
container + " :done waiting for " + seconds + " seconds"
}
This won't produce exactly the output you're asking for ("Function complete" will be printed first, and allTasks and singleTask aren't sequenced with respect to each other), but it will run the tasks in parallel on separate threads.
(As a footnote: the FuturePool.unboundedPool in my example above is an easy way to create a future pool for a demo, and is often just fine, but it isn't appropriate for CPU-intensive computations—see the FuturePool API docs for other ways to create a future pool that will use an ExecutorService that you provide and can manage yourself.)

Simple time changing .bat

is it possible to make a .bat file that would work like this :
Get current date in dd.mm.yyyy format
Change date to desired one
Wait 60s
Change date back to its original state
exit
I know i can get current date by echo %date% and i get it in format dd.mm.yyyy but I have no idea how change it through one command, "set date" it's not working for me. I also know I could change date by simple command "date" then enter date but don't know how to automatize it. Can anyone write something like this?
To change the date you need admin permissions !
You can do it like echo 05.12.15|date
You can see how you can see how to get the date in a specific format and here you can see few tricks how to wait in batch .
Here's the script - (run it with admin privileges !):
#if (#X)==(#Y) #end /* jscript commend
#echo off
set "desired_date=03.12.15"
:: execute jscript part and get the date in a specific format
for /f "tokens=1-3 delims=- " %%A in ('cscript //E:JScript //nologo "%~f0"') do (
set fdate=%%C.%%B.%%A
)
rem echo %fdate%
::change date
echo %desired_date%|date
::wait 60 seconds
typeperf "\IPv4\Datagrams Received/sec" -si 60 -sc 1 >nul 2>nul
::return date to its original state
echo %fdate%|date
exit /b 0
end of jscript commend*/
function GetCurrentDate() {
// Today date time which will used to set as default date.
var todayDate = new Date();
todayDate = todayDate.getFullYear() + "-" +
("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" +
("0" + todayDate.getDate()).slice(-2) + " " + ("0" + todayDate.getHours()).slice(-2) + ":" +
("0" + todayDate.getMinutes()).slice(-2);
return todayDate;
}
WScript.Echo(GetCurrentDate());