# Working with DynamicModule: ScheduledTasks with local variables

I have a question - is it possible to run ScheduleTask[] inside DynamicModule[]?

What I have tried so far:

DynamicModule[
{
Dynamic[i]
}
]


It was supposed to increment and display value of i after "Run" was clicked, however it did not.

If you run ScheduledTasks[] you can notice that the task was created however it is not running... Any idea how to fix this one (if it is possible)?

Ok, thanks for answers guys however I have one more thing troubling me. What if I want to run specific, predefined tasks? E.g.:

DynamicModule[{i = 0, t1, t2},

Button["Run t2", StartScheduledTask[t2]], " ", i}]
]


Of course this one is just an error generator but it presents general concept of what I would like to achive;p I would be grateful if you fix and explain this last one for me!

• You can confirm with Print that the task does run. As Kuba says, the problem is that the argument of Dynamic is not evaluated. The second problem is that Dynamic[i] does not seem to realize that i is changing value, which you can fix with Dynamic[i, UpdateInterval -> 1]. – C. E. Jan 4 '16 at 18:49

### Some notes

• First of all Dynamic[++i] does nothing unless it is displayed, and ScheduledTask is evaluated in Kernel without sending DynamicBoxes to the Notebook.

Correct syntax: use ScheduledTasks[++i...]

• There is a that affects crude Dynamic[var], where var is a DynamicModule's variable.

It makes Dynamic[var] not aware of changes of var unless they are done via PreemptiveLink, it is discussed in

Quick fix: use e.g.: Dynamic[ First @ List @ x].

What if I want to run specific, predefined tasks?

I'm not 100% sure why the message:

StartScheduledTask::timnf : Specified task ScheduledTaskObject[


is generated but here is my (quite solid) guess and the solution:

• Explanation

It seems that ScheduledTasks are not found by mentioned id but the full form of the ScheduledTaskObject. And the object you created is different than the one which is called from the Button, here it is why:

The problem is that i is fully scoped (by DynamicModule) when the DM is displayed (DynamicModule converted to DynamicModuleBox).

When the body (2nd argument of DM) with your definitions evaluates DynamicModule scopes similarly to Module so it creates x\$123. Yet at the end it will rename it again to x$$123 (shortly, it is a longer topic). ScheduledTaksObjects in ScheduledTaks[] contain reference to this i123 while DynamicModule keeps ScheduledTaskObjects which underwent the second stage of scoping and i123 was replaced with i$$123 (more or less).

We can check that this is really the case:

 DynamicModule[{x, t},
Print @ Column @ {
InputForm @ t,
}
]
]


Knowing that, and knowing that Initialization is sent to the evaluation after that second stage of scoping, we can deduce the fix.

• Quick fix: move your definition to the Initialization of DynamicModule.

### Final fixed code:

DynamicModule[ {i = 0, t1, t2},
Column[{
" ",
Dynamic @ First @ List @ i}]
,
Initialization :> (
)
]


For more detailed discussion of a closely related issue, take a look at:

Scheduled tasks work fine within DynamicModule. For the past 3 years several schools here have trialled a Mathematica based final year math exam which included nested tasks (for reading time, writing time, restarting and so on) within one large dynamic module.

 DynamicModule[{i = 0},

Column[{
Button["Run",
If[i == 6,
Button["Stop",
],
Button["Reset", i = 0],
Dynamic[{i}]
}]
]

• Is there any public info about details of those projects? – Kuba Jan 5 '16 at 8:38
• @kuba depends what you mean by public info. By definition the state education system know about it. WRI know about it. The code is not public. The exam is distributed to schools by SFTP on exam day. – Mike Honeychurch Jan 5 '16 at 9:01
• I mean something that one could learn something from :) – Kuba Jan 5 '16 at 10:01
• @kuba i am on my phone now but can give a description tomorrow. I cant post the code but even though it is reasonably long it doesnt have anything that would be new to you – Mike Honeychurch Jan 5 '16 at 10:59
• @kuba I can email if you like but for backup there was a scheduled task for autosaving every 2 minutes (plus a manual save button) plus multiple choice sections of the exam were stored as tagging rules and also exported as a file upon completion. A knowledgeable student, if the knew scheduled tasks were used, could of course stop all tasks but that would be the same as tearing up a paper exam. The menu was temporarily altered during the exam to limit what students had access to – Mike Honeychurch Jan 5 '16 at 22:50

# WARNING

my original answer actually gives the wrong impression that there is a problem with ScheduledTasks and DynamicModule which actually is not the case, see my edit below the original answer. Of course my findings are just what Kuba has already found before. My (newer) code doesn't need the fix for the initialization as all code is in Button callbacks anyway. I would suggest the OP to accept Kuba's answer as it solves all the problems he originially had...

# ORIGINAL

I think you just found that ScheduledTaskObjects don't behave well when they are made local variables of DynamicModules. Here is code along the lines of what you try to do which seems to work (Mathematica 10.3 on Windows):

DynamicModule[{},
i = 0;
Row[{
Dynamic[i]
}]
]


But as soon as you try to put either i or task into the list of local variables it won't work anymore. I find it not too surprising that this doesn't work, but as it nowhere is documented that it doesn't work, it might be considered a bug. A workaround is to use other ways to localize the variables you are using there...

# EDIT

I just realized that my answer and the one of Mike are in contradiction, me showing code that doesn't work while he is showing code which obviously works. So I tried to understand the differences and found that Mike is right with stating that the combination of DynamicModule local variables and ScheduledTasks in fact works well. The problem is with certain forms of Dynamic, as can be seen from my (slightly changed) example with localized variables which does not work as expected:

DynamicModule[{task, i = 0},
Row[{
Button["start",
i = 0;
];
],
Dynamic[i]
}]
]


But as it turns out the only problem is that the Dynamic[i] does not update as required. If we change it to Dynamic[{i}] as in Mikes working code the above code will work. A more general approach to fix this is to explicitly add the TrackedSymbols option as here:

DynamicModule[{task, i = 0},
Row[{
Button["start",
i = 0;
];
],
Dynamic[i,TrackedSymbols:>{i}]
}]
]


so I think this shows that there is no problem with using DynamicModule local variables and ScheduledTasks but that one has to be careful to not run into a problem with Dynamic which also has been discussed on this site before, see e.g. here, here or here.

One final warning: if you use Mikes code naively in your own code you are in the danger to remove and stop scheduled tasks that might exist independently of the shown dynamic module. So it might be safer to use a local variable to remove and stop the given task than just to do that for all currently existing ScheduledTasks[]. Of course his code is perfectly fine for making his point in demonstrating that ScheduledTasks and DynamicModule local variables do work together and because they do it is easy enough to localize the scheduled task as in my code above.

This functions

DynamicModule[{i = 0},
Dynamic@Row[{Button["Run", RunScheduledTask[++i, 1]], " ", i}]]


Update

Module[{i = 0, t1},

I didn't find a way to make this run inside a DynamicModule.
• So this all was fault of misusing Dynamic[] wrap around i? But... why? Mayby I misunderstood the whole Dynamic concept but i thought if you want to see how the variable changes you should write it like Dynamic[var].... – michelson Jan 4 '16 at 18:50
• Module approach won't work if you deploy it as a CDF or simply save the notebook with that interface. Next time you open MMA and this notebook, there will be no trace of t1 definition. – Kuba Jan 5 '16 at 8:29