JavaScript examples that have worked for you. Put them here for others to use

If you have JavaScript examples you have used then put them here so others can cut and paste them to help getting used to using JavaScript rules.
Don’t put DSL rules here as it will get confusing.
I have had problems trying to find JavaScript examples in the past and then I had to work out whether it was DSL or JavaScript as they are similar.
Anyway having said that I will put some examples of what has worked for me. Feel free to modify/correct/improve as I am definitely NOT a JavaScript expert/programmer. I have just cut and pasted from other examples to get my system up and running.

Click to see example JavaScript code!
  //This contains things that I have found that work in javascript
//More information here:

//need below to log to openhab.log file
var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);
//below is if you are going to use the ececute command
var Exec = Java.type("org.openhab.core.model.script.actions.Exec");
//below is also neede for the execute command
var Duration = Java.type("java.time.Duration");

//below is example of executeComand
Exec.executeCommandLine(Duration.ofSeconds(5), "/usr/bin/mosquitto_pub","\-h","","\-t","cmnd/coffee/displaytext","\-m","[zOa2f0s1l1c1]" + device + "[s3l2c1]" +stateof + "[s1l8c1]Updated[c9]at:[c13tS]");

//This is the tricky part to get the triggering item. It uses event and event does NOT exist until the trigger
//has run and that is what creates the event. You CANNOT just press run now from the editor
//and expect it to work. It MUST be tested using an item trigger.

//below is get the triggering item Label
var device = itemRegistry.getItem(event.itemName).getLabel();
//or you can use the shorthand version
var device = ir.getItem(event.itemName).getLabel();

//below is to get the triggering item command from the item
var stateof = event.itemCommand ;

//below is an example to test the triggering event and see the old state and the new state[itemRegistry.getItem(event.itemName).getLabel(), 'Changed From:', event.oldItemState ? event.oldItemState : 'Null', 'To:', newState].join(' '));

//below is how to get the state of an item
var rfinput = itemRegistry.getItem('RFBridgekitchen_Receiveddata').getState();

//below is example of logging'Back door opened' + variablename);

// below is a sleep funtion to slow down execution. I want to flash a lamp 3 times
function sleep(milliseconds) {
  date =;
  currentDate = null;
  do {
    currentDate =;
  } while (currentDate - date < milliseconds);
if (itemRegistry.getItem('Doorgarage_Doorgarage').getState() == 'OPEN' || itemRegistry.getItem('DoorshedLH_DoorshedLH').getState() == 'OPEN') {
  for (var count = 0; count < 3; count++) {
    events.sendCommand('Zigbeesengledbulb_Zigbeesengledbulb', 'ON');
    events.sendCommand('Zigbeesengledbulb_Zigbeesengledbulb', 'OFF');'Door open somewhere');
    events.sendCommand('Zigbeesengledbulb_Zigbeesengledbulb', 'ON');
// end of sleep example

//below is an example of how to send email assuming you have the mail binding correctly set up
//the mail:smtp:a514b96247 is found by looking at the mail thing

//below is how to sent html email with multiple attachemments (NOTE the plural of attachments)
var ArrayList = Java.type('java.util.ArrayList');
message = "<H2>Someone is at the front door at " + Date() + "</H2>";
attachmentUrlList = new ArrayList();
actions.get("mail", "mail:smtp:a514b96247").sendHtmlMailWithAttachments("", "openHAB 3 front door bell", message , attachmentUrlList );

//below is how to post an update to an item
events.postUpdate('Doorcat_Doorcat', 'CLOSED');

//below is how to send a command to an item
events.sendCommand('CoffeeMachine_CoffeeMachine', 'OFF');

//below is how to test a value of an item and then do something
  if (itemRegistry.getItem('Tricklecharger_Tricklechargerpower').getState() < '5') {
  events.sendCommand('Tricklecharger_Tricklecharger', 'OFF');
//'Script ran inner loop');

//I have left the code in to calculate the day etc as it was a pain to find any docs about it.
//calculate the day number
var datetoday = new Date();
var numberofweek = datetoday.getDay();

//if it is not NIGHT then change colour
if (itemRegistry.getItem("LocalSun_SunPhaseName").getState() != 'NIGHT') {

 if (numberofweek == 0){
 //It is Sunday and that week day is 0 and that doesn't work with the colour
  //set it to 7
  numberofweek = 7 ; 
  numberofweek = 5  //green
//it is NIGHT so only do red light  
  numberofweek = 1  //red

//end of calculate the day of the week

//this is how to find and replace - with _
events.postUpdate(itemRegistry.getItem(event.itemName).getName(), itemRegistry.getItem(event.itemName).getState().toString().replace(/-/g, '_'));

//Get the weeday name
var datetoday = new Date();
//var numberofweek = datetoday.getDate();
var weekday = datetoday.toLocaleString("default", { weekday: "short" })

//get list of group members
itemRegistry.getItem("gAllLights") { events.sendCommand(, i.state.toString()); } );

var whatitis = "";
                   .filter(function(batt) {return batt.state.intValue() <= 10; } )
                   .forEach(function(batt) { whatitis = whatitis + batt.label +": "+ batt.state +"%" + "\r\n"; } );
if(whatitis != ""){
    events.sendCommand('TelegramText', "Batteriewarnung für: \r\n" + whatitis);

//below will list all items and states in a group
var whatitis = "";
                   .forEach(function(batt) { whatitis = whatitis + batt.label +": "+ batt.state + "\r\n"; } );
if(whatitis != ""){
//    events.sendCommand('TelegramText', "Batteriewarnung für: \r\n" + whatitis);'\r\nGroup list: \r\n' + whatitis );

//below is json parse
var obj = itemRegistry.getItem("BOMdata").getState();
var test = JSON.parse(obj) ;

for (var count = 0; count < 7; count++) {'Icon: ' +[count].icon_descriptor);'Short text: ' +[count].short_text);'Date: ' +[count].date);'Max: ' +[count].temp_max);'Min: ' +[count].temp_min);'Forecast ' +[count].extended_text);

//More information here:
var OPENHAB_CONF = Java.type('java.lang.System').getenv('OPENHAB_CONF');

//need below to log to openhab.log file
var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);
//below is if you are going to use the ececute command
var Exec = Java.type("org.openhab.core.model.script.actions.Exec");
//below is also neede for the execute command
var Duration = Java.type("java.time.Duration");

//var HttpUtil = Java.type("");
var HttpGet = Java.type("org.openhab.core.model.script.actions.HTTP");

//because icon names with dashes in them are reserved I replace the dash with underscore
function input(i) {
    return i.replace(/-/g,'_');

//var DATA = HttpUtil.executeUrl("GET","", 2000).replace(/icon_descriptor...\w+/g,input);
var DATA = HttpGet.sendHttpGetRequest("", 2000).replace(/icon_descriptor...\w+/g,input);

events.postUpdate("BOMdata", DATA);

//this is how to run a script file
var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");
var _bundle = FrameworkUtil.getBundle(scriptExtension.class);
var bundle_context = _bundle.getBundleContext()
var classname = "org.openhab.core.automation.RuleManager"
var RuleManager_Ref = bundle_context.getServiceReference(classname);
var RuleManager = bundle_context.getService(RuleManager_Ref);
RuleManager.runNow("8e1e6893d6"); //the 8e1e6893d6 is the id of the script found when you look in the script list

//Stuff below keeps the results so you can run scripts and use the this.Storage result                   
//below is to create a global array
//this.Storage = (this.Storage === undefined) ? [] : this.Storage;
this.Storage = (this.Storage === undefined) ? 1 : this.Storage;
//below is to create a global number
this.Storage = this.Storage + 1;

These 2 statements are the do the same thing:["CoffeeMachine_CoffeeMachine"])"CoffeeMachine_CoffeeMachine").getState())

//below splits the results comma separated
var test = itemRegistry.getItem("LightHall_Lighthallcolour").getState().toString().split(",");"Test " +  test);"Test " +  test[0]);"Test " +  test[1]);"Test " +  test[2]);"Hue " + items["LightHall_Lighthallcolour"].getHue());"Saturation " + items["LightHall_Lighthallcolour"].getSaturation());"Brightness " + items["LightHall_Lighthallcolour"].getBrightness());

  //below will list all items and states in a group
var whatitis = "";
                   .filter(function(batt) {return batt.state.intValue() <= 45; } )
                   .forEach(function(batt) { whatitis = whatitis + batt.label +": "+ batt.state + "\r\n"; } );
if(whatitis != ""){
//    events.sendCommand('TelegramText', "Batteriewarnung für: \r\n" + whatitis);'\r\nGroup list: \r\n' + whatitis );
//below gets the historical sate if an item
var PersistenceExtensions = Java.type("org.openhab.core.persistence.extensions.PersistenceExtensions");
var ZonedDateTime = Java.type("java.time.ZonedDateTime");

var myPersistentItem = ir.getItem("Zigbeesengledbulb_Zigbeesengledbulb");"The pyload is {}", myPersistentItem);

var sinceDate =;
//var sinceDate =;

var maximumValueSince = PersistenceExtensions.maximumSince(myPersistentItem, sinceDate);"Historic item is {}", maximumValueSince);"Item name is {}",;"Item state is {}", maximumValueSince.state);

//below is logic for a javascript timer. I have used similar in the coffee machine on off logic
var logger          = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID); 
    var ScriptExecution = Java.type("org.openhab.core.model.script.actions.ScriptExecution");  
    var ZonedDateTime   = Java.type("java.time.ZonedDateTime");  
var Exec = Java.type("org.openhab.core.model.script.actions.Exec");
var Duration = Java.type("java.time.Duration");

//set up the timercoffee
  var TimerMinutes = 55;"Coffee timer minutes: "+TimerMinutes);
if (this.timercoffee != undefined) {
      this.timercoffee.cancel();"Coffee timer undefined: ");

    function displaywaring() {
      Exec.executeCommandLine(Duration.ofSeconds(5), "/usr/bin/mosquitto_pub","\-h","","\-t","cmnd/coffee/displaytext","\-m","[zOf0s2]Coffee[c1l2]machine[c1l3]OFF in 5[c1l4]minutes.~3");
//"CoffeeMachine_CoffeeMachine turned "+items["CoffeeMachine_CoffeeMachine"]);
      this.timercoffee = undefined;
  "Sending message to display: ");

    this.timercoffee = ScriptExecution.createTimer(, displaywaring);

results = Exec.executeCommandLine(Duration.ofSeconds(5), "/usr/bin/mosquitto_pub","\-h","","\-t","cmnd/coffee/displaytext","\-m","[zOf0s2]Coffee[c1l2]machine[c1l3]is now off[c1l4]Bye.~3");
//If off then cancel the timercoffee
  if (this.timercoffee != undefined) {
      this.timercoffee.cancel();"Cancelled timer for coffee machine: ");
    }else{"Expired timer coffee machine: ");}

  //Get a time in between two times:
  if ((, 0))) && (, 0)))) {

//parse json data:
  var test = JSON.parse('{"localNumber":"012345","remoteNumber":"012345","date":"2021-06-26T17:55:00+02","type":2,"duration":0}')"test: " + test.remoteNumber)"date: " +

Hopefully this will help people just starting out. I have only been using JavaScript for a few months.


Thanks for the code. Maybe you could add codefences to make it more readable. I’ll bookmark this to share my javascript stuff. I’m also fairly new to it.

I did have code fences but they disappeared when I posted.
I have put them back in again.
Hope you find a use for the code. Some of the information in there was hard to find.

For future repliers, please use code fences in your replies.


code goes here


Or if posting a full rule use


code goes here


General advice:

  • Use the --Scratchpad-- Script to experiment. You can access it from the Developer Sideboard

  • Once you figure something out, save it to a Script so that you build up a local library of examples.

None of the below Script Actions use the Helper Library. Many of them can be significantly simplified if they did.

Create a rule from another rule

NOTE: This doesn’t quite work right; posting in case someone wants to run with it.

// Create a new rule

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");"Typing needed classes");





var RuleBuilder = Java.type("org.openhab.core.automation.util.RuleBuilder");

//var ModuleBuilder = Java.type("org.openhab.core.automation.util.ModuleBuilder");

//var Configuration = Java.type("org.openhab.core.config.core.Configuration");"Creating the trigger");

var newTrigger = ModuleBuilder.createTrigger().withId("Item-aTestSwitch-received-update").withTypeUID("core.ItemStateUpdateTrigger").withConfiguration( new Configuration( { "itemName": "aTestSwitch" })).build();

var triggers = [newTrigger];

var runme = function(event) {

  var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Experiments");"Inside created rule!");

}"Building the rule")

var execX = new SimpleRule() { execute: runme };

var rule = RuleBuilder.create("createdrule")

                      .withName("Created Rule")

                      .withDescription("Rule created from Experiments rule")



                      .build();"Registering the rule");

automationManager.addRule(rule);"Waiting a bit...");

java.lang.Thread.sleep(5000);"Trying to call the created rule");

var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");

var _bundle = FrameworkUtil.getBundle(scriptExtension.class);

var bundle_context = _bundle.getBundleContext()

var classname = "org.openhab.core.automation.RuleManager"

var RuleManager_Ref = bundle_context.getServiceReference(classname);

var RuleManager = bundle_context.getService(RuleManager_Ref);



var triggers = thisRule.getTriggers();"There are " + triggers.length + " triggers on this rule");"Typing the Configuration");"Creating the trigger")

var newTrigger = ModuleBuilder.createTrigger().withId("Item-vIsCloud-received-update").withTypeUID("core.ItemStateUpdateTrigger").withConfiguration( new Configuration( { "itemName": "vIsCloudy" })).build();"Added the trigger to the list");


logger.infoinfo("Adding the triggers to the Rule");

thisRule.setTriggers(triggers);"There are now " + thisRule.getTriggers().length + " triggers on this rule");



var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Expamples");"About to test createTimer");

var ScriptExecution = Java.type("org.openhab.core.model.script.actions.ScriptExecution");

var runme = function(){"Timer expired!"); }

var ZonedDateTime = Java.type("java.time.ZonedDateTime");

var now =;

var timer = SE.createTimer(now.plusSeconds(1), runme);

Disable another rule

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");

// Find the rule"There are " + rules.getAll().length + " rules");

for each (var r in rules.getAll()) {"Rule name = " + r.getName());"Rule UID = " + r.getUID()); 


var thisRule = rules.getAll().stream().filter(function(i){ return == "Experiments" }).findFirst().get();"This rules UID is " + thisRule.getUID());

// Disable the rule

var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");

var _bundle = FrameworkUtil.getBundle(scriptExtension.class);

var bundle_context = _bundle.getBundleContext()

var classname = "org.openhab.core.automation.RuleManager"

var RuleManager_Ref = bundle_context.getServiceReference(classname);

var RuleManager = bundle_context.getService(RuleManager_Ref);"Enabled = " + RuleManager.isEnabled(thisRule.getUID()));

RuleManager.setEnabled(thisRule.getUID(), false);"Enabled = " + RuleManager.isEnabled(thisRule.getUID()));


// Ephemeris

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");"About to test Ephermeris");

var Ephemeris = Java.type("org.openhab.core.model.script.actions.Ephemeris"); ? "It's the weekend" : "Get back to work!");


// Exec.executeCommandLine

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");"About to test executeCommandLine");

var Exec = Java.type("org.openhab.core.model.script.actions.Exec");

var Duration = Java.type("java.time.Duration");

var results = Exec.executeCommandLine(Duration.ofSeconds(1), "echo", "hello");"results = " + results);

HTTP POST Using Native Java and Base64 encoded auth

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Honeywell");

var URI = Java.type("");

var URLEncoder = Java.type("");

var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");

var HttpClient = Java.type("");

var HttpRequest = Java.type("");

var HttpResponse = Java.type("");

var Base64 = Java.type("java.util.Base64");"Requesting new authcode");

this.client = (this.client === undefined) ? HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build() : this.client;

var grant_type = "authorization_code"

var redirect_uri = URLEncoder.encode("", StandardCharsets.UTF_8);

var code = items["Honeywell_AuthCode"].toString();

var data = "grant_type="+grant_type


           +"&code="+code;"Data to send: " + data);

var body = HttpRequest.BodyPublishers.ofString(data);

var authStr = items["Honeywell_APIKey"].toString()+":"+items["Honeywell_APISecret"].toString();

var auth = Base64.getEncoder().encodeToString(authStr.getBytes("UTF-8"));"Encoded auth: " + auth);

var testStr = "9UY8NrmDtIh8GVTkNdX0Y7I6k37254a9:Z1947381rwgf0WkPPGPHnGik6h3LdhZ9";

var expected = "OVVZOE5ybUR0SWg4R1ZUa05kWDBZN0k2azM3MjU0YTk6WjE5NDczODFyd2dmMFdrUFBHUEhuR2lrNmgzTGRoWjk=";

var encoded = Base64.getEncoder().encodeToString(testStr.getBytes());

(encoded == expected) ?"Encoding success!") : logger.error("Encoding failure!");

var request = HttpRequest.newBuilder()



                  .setHeader("User-Agent", "Java 11 HttpClient Bot")

                  .header("Content-Type", "application/x-www-form-urlencoded")

                  .header("Accept", "application/json")

                  .header("Authorization", "Basic " + auth)

                  .build();"Built the request: " + request.toString() + " " + request.headers() + " " + request.bodyPublisher().toString());

var response = this.client.send(request, HttpResponse.BodyHandlers.ofString());"Status code: " + response.statusCode());"Body       : " + response.body());

Item Metadata

// Accessing Item Metadata

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");"Trying to extract a metadata value")

var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");

var _bundle = FrameworkUtil.getBundle(scriptExtension.class);

var bundle_context = _bundle.getBundleContext()

var classname = "org.openhab.core.items.MetadataRegistry"

var MetadataRegistry_Ref = bundle_context.getServiceReference("org.openhab.core.items.MetadataRegistry");

var MetadataRegistry = bundle_context.getService(MetadataRegistry_Ref);

var methods = MetadataRegistry.class.getDeclaredMethods();"There are " + methods.length + " methods");

for each (var m in methods) {;


var Metadata = Java.type("org.openhab.core.items.Metadata");

var MetadataKey = Java.type("org.openhab.core.items.MetadataKey");

var metadata = MetadataRegistry.get(new MetadataKey("name", "vArgus_Status"));"vArgus_Status's name is " + metadata.value);

event.itemState type stuff

// Get the state of an Item

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");"The state of ServiceStatuses is " + items.ServiceStatuses);"The triggeringItem is " + event.itemName);"The command received is " + command);

// oldState/newState with changed trigger

// state with update trigger

// Command/update an Item

events.postUpdate(event.itemName, "OFF");

events.sendCommand(event.itemName, "ON");

Loading Personal Libraries

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Dad Motion");

this.ZonedDateTime = (this.ZonedDateTime === undefined) ? Java.type("java.time.ZonedDateTime") : this.ZonedDateTime

var OPENHAB_CONF = java.lang.System.getenv("OPENHAB_CONF");




openHAB’s Log Actions

var Log = Java.type("org.openhab.core.model.script.actions.Log");

Log.logError("Experiments", "This is an OH error log");

Log.logWarn("Experiments", "This is an OH warn log");

Log.logInfo("Experiments", "This is an OH info log");

Log.logDebug("Experiments", "This is an OH debug log");

// There is no trace

Map/Reduce Members of a Group

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Scratch");

this.Collectors = (this.Collectors === undefined) ? Java.type("") : this.Collectors;"Chromecast_Idle")



       .filter(function(cc) { return cc.state == OFF; })

       .map(function(cc) { 

         var devName =[0];

         return cc.label.replace(" Idling", "") + " | " + items[devName+"_App"] + " | " 

           + items[devName+"_MediaType"] + " | " + items[devName+"_MediaArtist"] + " | " + items[devName+"_MediaTitle"];



Save variables from one run to the next

// Saving values from one run to another

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");;"test_count = " + this.test_count);

if(this.test_count === undefined) {

  this.test_count = 0;

}"test_count = " + this.test_count);

this.test_count += 1;"test_count = " + this.test_count);

Run Another Rule

// Run another rule

var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");

var _bundle = FrameworkUtil.getBundle(scriptExtension.class);

var bundle_context = _bundle.getBundleContext()

var classname = "org.openhab.core.automation.RuleManager"

var RuleManager_Ref = bundle_context.getServiceReference(classname);

var RuleManager = bundle_context.getService(RuleManager_Ref);


var map = new java.util.HashMap();

map.put("test_data", "Passed data to called function!")

RuleManager.runNow("tocall", true, map); // second argument is whether to consider the conditions, third is a Map<String, Object> (way to pass data)


// Sleep

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");"About to sleep");

java.lang.Thread.sleep(1000);"Done sleeping");

Units of Measurement (QuantityTypes)

// QuantityTypes

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");"Cloudiness = {}", items["vCloudiness"]);"Coudiness without QuantityType = {}", 

            parseFloat(items["vCloudiness"].toString().split(' ')[0]));"New QuantityType = {}",

            new QuantityType("50.0 %"));"Comparison to QuantityType = {}", 

            items["vCloudiness"] > new QuantityType("50.0 %"));

Script Conditions


  - id: "1"


      itemName: Presence

      state: ON

      previousState: OFF

    type: core.ItemStateChangeTrigger


  - inputs: {}

    id: "2"


      itemName: MasterBedroomSensors_LightLevel

      state: "100"

      operator: <

    type: core.ItemStateCondition

  - inputs: {}

    id: "4"


      type: application/javascript

      script: items["TimeOfDay"] != "NIGHT" && items["TimeOfDay"] != "BED";

    type: script.ScriptCondition


  - inputs: {}

    id: "3"


      type: application/javascript

      script: >

        var logger =



"Welcome home! Turning on the MBR Lights!");

        events.sendCommand("MasterBedroomLights_Power", "ON");

    type: script.ScriptAction


Does someone have a simple example of a timer-based rule in file-based JSR223, say a rule that triggers every ten minutes?

According to this:

Javascript now apes Python decorators, but I’m damned if I can make sense of the (single) item change-based example in that post. Are the triggers like CronTrigger and ItemStateChangeTrigger obsolete? I’m very confused.

Normally you should just use the cron-based Trigger for triggering rules in an interval.
From my understanding even in OH3, you should avoid (longer) sleeps and minimize the use for timers within a rule. It makes the rule logic not only more complicated, but also uses more memory as needed…

The cron-based trigger is what I want. I just want an example of a rule triggered by a timer in OH3. It appears that the triggers from OH2 are now completely broken.

To clarify: this is the sort of thing I had working in OH2.

    name: "Run every 10 minutes",
    description: "Do stuff",
        TimerTrigger("0 0/10 * * * ?")
    execute: function( module, input)
          // Do stuff

What would the equivalent in OH3 be?

  - id: "1"
      cronExpression: 0 0/10 * * * ? *
    type: timer.GenericCronTrigger
conditions: []
  - inputs: {}
    id: "2"
      type: application/javascript
      script: >-
        var logger =
"log some stuff");
    type: script.ScriptAction

this would trigger a log-entry every 10mins.
You can invoke a script/rule/execCommand/… within that script of course… but I don’t get your use case of using cron within a rule?

That goes in a .js file? What syntax is that?
I’m totally lost at this point.

@LordLiverpool how many places are we having this conversation lol.

Your example in this post is the correct syntax and should be working.

Haha. The “My first steps” post is really a kind of running blog of my attempt to get my openHab system working. When I have a specific problem I can’t solve, I open a thread. This seemed like a good place to find examples, but I get the impression that “Javascript” has fragmented into several different implementations and syntaxs, including the one generated by the new UI in OH3. So it’s difficult to keep track of.

I’m going to try it, and if it works, I’ll post it here.

  1. read through the intros for OH3
    Getting Started - Introduction | openHAB
    especially the part about “rules”
    Rules | openHAB
  2. in OH3 goto “Settings” - “Rules”
  3. click on the plus in the down-right corner
  4. click on “code” and insert said code

I’m not using the UI, I’m using .js files. I’m not sure the two methods can be combined.

I think we’re talking about two completely different things.

in a way - yes. You want to start JavaScript with a cron - usually that’s where Rules (with ECMA-Script) come into place. That’s why I started this.

…if you need - for some reason or the other - the .js script: you can start a .js script from a Rule (as described above).

I’m coming from an OH2 setup where all my rules are in .js files. I prefer not to get involved with the UI if possible.

Pro-Tipp: use the UI, it saves A SH%TLOAD of trouble[1]. (and that’s coming from a guy, who’s file-based thinking is decades old)

nonetheless: you could create rules outside the UI, but then again: why bother? text files are error-loaden, non-referential and mostly impractible. - the only upside is: you can git and backup them more easily than the OH3 UI. But then again: I backup my OH3 daily and you can git and backup your JSON-DB also…

[1] first of all: you get more and better support here in the forum using the UI.
Second: you can’t get errors in referencing with typos and stuff, as you the UI takes care of the references
Third: you don’t have the hassle with naming conventions and loading of item-files and referencing the correct things and having to dig deep to get the right thing-syntax - that does the UI and the binding for you.

I don’t know how to use cron-timer in .js files and that’s I imagine not the recommended way - so you’re probably on your own with this approach. :man_shrugging:

I prefer to edit my files on the PC in Visual Code and then copy them over as needed. Much easier to backup, easier to edit, easier in every way.

Yes, it looks like I’m on my own with the file-based approach. Oh well.

I’ve already figured out how to set up the timer trigger.