Calculate the Duration after Toggle switch turns on

I was thinking to use Tag.Timestamp property of a Boolean memory tag "NotScheduled" as starttime and now() as current time to get the difference.
This script appears to work half way, when I set another integer type memory tag "notScheduledTime" the tag value to 100 and run this, it changes to 0, I think the else logic part appears to work. But it was not updating the tag with duration minutes.
I would appreciate your help.

def valueChanged(tag, tagPath, previousValue, currentValue, initialChange, missedEvents):

	import system
	# Define tag paths
	durationTag = ["[.]../Performance/notScheduledTime"]
		
	if 	currentValue.value == True:
		currentTime = system.date.now()
		startTime = currentValue.timestamp
		minutes = system.date.minutesBetween(startTime,currentTime)
		
		if minutes >=1:
			minutes += 1
		system.tag.writeBlocking(["[.]../Performance/notScheduledTime"], [minutes])
	else:
	    # when toggled to False, reset duration to zero
	    system.tag.writeBlocking(["[.]../Performance/notScheduledTime"], [0])
  1. Don't import system. It's built in.
  2. Don't run scripts like this on tag value changed. There is a limited pool of threads (3) and system.tag.writeBlocking can gum it up.

Always, if you can, use an expression rather than a script. Try this expression in notScheduled:

round(
	(now() - {[~]notScheduledTime.Timestamp}) / 60000,
	0
)

While you test it out set the Data Type to Float and round() to three decimal places so you don't have to wait a minute to see the change.

The expression will update at the default scan class rate. If every 5 s is good enough then change now() to now(5000), etc.

1 Like

Use minutesBetween in your expression.

if([~]Performance/notScheduledTime,
   minutesBetween([~]Performance/notScheduledTime.Timestamp, now()),
   0)
2 Likes

@Transistor Thank you for highlighting the issues with my approach and suggesting alternatives.
@JordanCClark - thank you for simplified expression.

writeAsync is OK though, if you don't need to wait for it to write before continuing. Actually, writeBlocking is fine here too as it's writing to a memory tag