Calculating difference between timestamps with varying zone information in Mule 4

This week, I was designing a queue monitoring solution in the simplest possible way I could to alert users via email. One of the programming tasks was to determine the time elapsed from last 6 hours (for example).

I used Mule 4's Scheduler component, a near replacement to Poll scope in Mule 4 in function to trigger my processing logic.

Image showing execution of both paths


every 6 hours, wake the flow to let my logic check if no message has been received into queue for 6 hours or more. If so, send an alert else log to console that everything is cool

The email sending part was implemented later with the email connector.

TIP: If you are seeing an error on the lines of 'You need to initiate with a STARTTLS command' from the actual server, you may want to place mail.smtp.starttls.enable="true" in the 'Advanced' section of configuration element where you can place custom properties.

This was the challenge I wanted to resolve for once and all which I would just comeback to whenever I want to in the future:

How do I handle the difference of timestamps in DW 2.0 of Mule 4 where I don't want to hardcode the timezone?

The pattern turned out to be good enough to be implemented in any other languages/frameworks I may work with in future. Yay! for re-usability and library-likeness.

I got to test both execution possibilities with 2 different test messages as shown in the previous image.

This is how the implementation looked by the end: Image showing dataweave code for subtracting timestamps

Here's the code you can re-use:

%dw 2.0
output application/java
var timeGap = (now() as LocalDateTime) - (payload as LocalDateTime)
var alertFlag = ( (payload as LocalDateTime) <= ((now() as LocalDateTime) - |PT6H|))
if (alertFlag) (
    "Alert: No message received from queues for the duration " ++ timeGap ++ " hours"
) else (
    "No alerts to report. Last message seen in period" ++ timeGap