How to create a timer in JSR223 (groovy) script

Hello there,

I am looking for a hint how to create a timer in a groovy based script.

My initial attempt was

createTimer(org.joda.time.Instant.now().plus(2000)) {
    logger.warn("timer expired")
}

but this leads to

Error: java.lang.NoClassDefFoundError: org/joda/time/Instant: org/joda/time/Instant

Dumping joda-time-2.10.2.jar into runtime/lib/ext solves this error (so is that really required?) but createTimer is still unavailable:

Error: groovy.lang.MissingMethodException: No signature of method: MyRule.createTimer() is applicable for argument types: (org.joda.time.Instant, MyRule$_execute_closure2) values: [2019-06-12T19:19:05.004Z, MyRule$_execute_closure2@3248f52a]: No signature of method: MyRule.createTimer() is applicable for argument types: (org.joda.time.Instant, MyRule$_execute_closure2) values: [2019-06-12T19:19:05.004Z, MyRule$_execute_closure2@3248f52a]

I guess I need to call createTimer on a ScriptExtension Object (https://www.openhab.org/docs/configuration/jsr223.html#scriptextension-objects-all-jsr223-languages), but which one?

Sources reveal just one possible Match: the static org.eclipse.smarthome.model.script.actions.ScriptExecution#createTimer … but ScriptExecution is not immediately available to my script:

org.eclipse.smarthome.model.script.actions.ScriptExecution.createTimer(org.joda.time.Instant.now().plus(2000)) {
    logger.warn("timer expired")
}

results in Error: java.lang.NoClassDefFoundError: org/eclipse/smarthome/model/script/actions/ScriptExecution: org/eclipse/smarthome/model/script/actions/ScriptExecution

Thanks

I played around with this a bit for my base classes. The joda time thing was something I ran into, but maybe a different issue. Anyway, here’s my code in case it is useful. I’m not sure it if still works at all or if it works in all cases. It was my first draft and I have a comment at the top that says “This is very much a work in progress…”

Doug

protected Timer createTimer(DateTime when, Runnable r) {
    Timer t = new Timer();
    final TimerTask tt = new TimerTask() {
        @Override
        public void run() {
            r.run();
        }
    };
    // joda DateTime.toDate() is blocked by osgi... do this the hard way for now
    org.joda.time.format.DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    String dtStr = fmt.print(when);
    logDebug("Setting timer set for " + dtStr);
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startDate;
    try {
        startDate = df.parse(dtStr);
        t.schedule(tt, startDate);
    } catch (ParseException e) {
        // shoudln't happen...
        logError("Unexpected parse exception setting timer", e);
    }

    return t;
}

Hi torpex77,

I was hoping for an official solution… but if there is none, I will try your solution and (kind of) rebuild the ScriptExecution#createTimer method.

Thanks