How To ... Call a MAXScript Function Periodically using DotNet

The following tutorials demonstrate the use of the System.Windows.Forms.Timer dotNetObject as alternative to the MAXScript Timer UI Control. Other than the latter, the DotNet object version does not require a MAXScript User Interface to be created and opened to run a MAXScript function at given time intervals.

Related topics:

DotNet In MAXScript

dotNetObject

dotNetObject:System.Windows.Forms.Timer

NATURAL LANGUAGE

Create a DotNet Timer Object if one doesn't already exist.

Define a counter for the number of times to call the function.

Define a MAXScript function to be called periodically by the timer.

Register an Event Handler to call the function

Set the timer interval.

Start the Timer.

EXAMPLE

if theTimer == undefined then (    
    theTimer = dotNetObject "System.Windows.Forms.Timer"
    counter = 20
    fn printTime = (
        counter-=1
        if counter < 1 then (
            print "stopping"
            theTimer.stop()
            theTimer = undefined
        )
        else (        
            print localTime
        )
    )
    dotnet.addEventHandler theTimer "tick" printTime
    theTimer.interval = 1000
    theTimer.start()
)

SAMPLE LISTENER OUTPUT:

undefined
OK
"2022-07-05 2:57:07 PM"
"2022-07-05 2:57:08 PM"
"2022-07-05 2:57:09 PM"
"2022-07-05 2:57:10 PM"
"2022-07-05 2:57:11 PM"
"2022-07-05 2:57:12 PM"
"2022-07-05 2:57:13 PM"
"2022-07-05 2:57:14 PM"
"2022-07-05 2:57:15 PM"
"2022-07-05 2:57:16 PM"
"2022-07-05 2:57:17 PM"
"2022-07-05 2:57:18 PM"
"2022-07-05 2:57:19 PM"
"2022-07-05 2:57:20 PM"
"2022-07-05 2:57:21 PM"
"2022-07-05 2:57:22 PM"
"2022-07-05 2:57:23 PM"
"2022-07-05 2:57:24 PM"
"2022-07-05 2:57:25 PM"
"stopping"
if theTimer == undefined then (    

Check whether theTimer has already been defined, for example if the script has already been run. Not doing this would re-assign theTimer to a new Timer object, and we would lose the reference to the original.

theTimer = dotNetObject "System.Windows.Forms.Timer"

Create a Timer.

counter = 20

Run the timer for 20 ticks.

    fn printTime = (
        counter-=1
        if counter < 1 then (
            print "stopping"
            theTimer.stop()
            theTimer = undefined
        )
        else (        
            print localTime
        )
    )

Define a MAXScript function to be called by the Timer. This function decrements the counter, and stops the timer when it gets to 0.

dotnet.addEventHandler theTimer "tick" printTime

Add ON TICK event handler to call the function.

theTimer.interval = 1000

Set the tick interval to 1 second (1000 milliseconds).

theTimer.start()

Start the Timer.