createTimer inside a lambda

Hi.

I’m using OH2.3.

I want to be able to create a timer inside a lambda function. Without it I’d use:

val int DELAY_REPEAT_ALARM 10
val int STATUS_AWAY 5

createTimer(now.plusSeconds(DELAY_REPEAT_ALARM)) [|
	Alarm_State.postUpdate(STATUS_AWAY)
	timer_repeat_alarm = null
	t_msg=""
]

The above code works correctly! When I trry


val Functions$Function2<int,int, Boolean> repeatAlarm = [ st , dly |
	logInfo('repeatAlarm',st)
	logInfo('repeatAlarm',dly)
	timer_repeat_alarm=createTimer(now.plusSeconds(dly.intValue)) [|
		Alarm_State.postUpdate(st.intValue)
		timer_repeat_alarm = null
		t_msg=""
	]
	true
]

repeatAlarm.apply(STATUS_AWAY,DELAY_REPEAT_ALARM)

I get this:

 Rule 'Alarm Condition': Could not invoke method: org.joda.time.DateTime.plusSeconds(int) on instance: 2018-08-05T19:46:19.641+01:00

How can I solve this?

Thanks.

As far i know, all variables that should visible out side of the lambda should be send to the lambda. Means the timer variable should be defined out side the lambda.

and now i read you error. dly.intValue is not possible because dly ist an int. Just try dly instead of dly.intValue

Thomas I think pointed out the error you are seeing but I see some other errors.

  1. Are you seeing any warnings in the logs or in VSCode about the <int, int, Boolean>? I didn’t think you could use primitives in the < >.

  2. timer_repeat is not declared inside the lambda. Global vals have no access and no visibility to each other so you would have to pass timer_repeat_alarm into the lambda. But what I don’t know is whether passing that variable and then reassigning it inside the lambda will cause the created Timer to be saved. You’d have to experiment.

  3. t_msg is not passed to the lambda either.

  4. Finally, this isn’t a problem but there is a cleaner way to define the lambda.

val repeatAlarm = [ int st, int dly |
	logInfo('repeatAlarm',st)
	logInfo('repeatAlarm',dly)
	createTimer(now.plusSeconds(dly.intValue)) [|
		Alarm_State.postUpdate(st.intValue)
		timer_repeat_alarm = null
	]
]
1 Like

@rlkoshak Number 4 is interesting. i never saw a definition like this. How is it used within a rule? And isn’t that a part for the Design Pattern?

It is just a way to define a lambda without the import of Functions and the need for all the awkward stuff one needs to use to define a lambda. The Rules DSL is smart enough to figure out what the lambda is (Function or Procedure) and what the types of the arguments and return value is on its own when defining a lambda like this.

Same as any other lambda. The lambda definition I provided is identical to Alexandre’s (with a couple of minor changes to the body).

I don’t use lambda in design patterns typically. I’ve not gone back to update Reusable Functions: A simple lambda example with copious notes yet.

Tanks, didn’t recognise the “Reusable Functions” To many DP too little time