9
$\begingroup$

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

What I have tried so far:

DynamicModule[
   {i = 0, task},
   {
       Button["Run",RunScheduledTask[Dynamic[++i], 1]],
       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},
 t1 = CreateScheduledTask[++i, 1];
 t2 = CreateScheduledTask[StopScheduledTask[t1]; --i];

 Dynamic@Row[{Button["Run t1", StartScheduledTask[t1]], 
    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!

$\endgroup$
  • $\begingroup$ 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]. $\endgroup$ – C. E. Jan 4 '16 at 18:49
8
$\begingroup$

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.

    You can read more about that in:

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

The answer

What if I want to run specific, predefined tasks?

I'm not 100% sure why the message:

StartScheduledTask::timnf : Specified task ScheduledTaskObject[
Unique ID : 18 Repetitions : \[Infinity]] is not found.

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 i$123 while DynamicModule keeps ScheduledTaskObjects which underwent the second stage of scoping and i$123 was replaced with i$$123 (more or less).

    We can check that this is really the case:

     DynamicModule[{x, t},
        t = CreateScheduledTask[x++, {1}];
        Button["Show tasks", 
           Print @ Column @ {
             InputForm @ t, 
             InputForm @ First @ ScheduledTasks[]
           }
         ]
     ]
    

    enter image description here

    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[{
   Button["Run t1", StartScheduledTask[t1]], 
   Button["Run t2", StartScheduledTask[t2]],
   " ",
   Dynamic @ First @ List @ i}]
 ,
 Initialization :> (
   t1 = CreateScheduledTask[++i, 1];
   t2 = CreateScheduledTask[StopScheduledTask[t1]; --i];
   )
 ]

Further reading

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

$\endgroup$
4
$\begingroup$

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", 
    RunScheduledTask[++i; 
     If[i == 6, 
      RunScheduledTask[CreateDocument["Hello world"], {1}]], {1,6}]],
   Button["Stop",
    StopScheduledTask[ScheduledTasks[]];
    RemoveScheduledTask[ScheduledTasks[]]
    ],
   Button["Reset", i = 0],
   Dynamic[{i}]
   }]
 ]
$\endgroup$
  • $\begingroup$ Is there any public info about details of those projects? $\endgroup$ – Kuba Jan 5 '16 at 8:38
  • $\begingroup$ @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. $\endgroup$ – Mike Honeychurch Jan 5 '16 at 9:01
  • $\begingroup$ I mean something that one could learn something from :) $\endgroup$ – Kuba Jan 5 '16 at 10:01
  • $\begingroup$ @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 $\endgroup$ – Mike Honeychurch Jan 5 '16 at 10:59
  • 1
    $\begingroup$ @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 $\endgroup$ – Mike Honeychurch Jan 5 '16 at 22:50
2
$\begingroup$

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;
  task = CreateScheduledTask[++i, 1];
  Row[{
    Button["start", StartScheduledTask[task]],
    Button["stop", StopScheduledTask[task]],
    Button["remove", RemoveScheduledTask[task]],
    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",
      If[Head[task] =!= ScheduledTaskObject,
        i = 0;
        task = CreateScheduledTask[++i, 1]
      ];
      StartScheduledTask[task]
    ],
    Button["stop", StopScheduledTask[task]],
    Button["remove", RemoveScheduledTask[task]; Clear[task]],
    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",
      If[Head[task] =!= ScheduledTaskObject,
        i = 0;
        task = CreateScheduledTask[++i, 1]
      ];
      StartScheduledTask[task]
    ],
    Button["stop", StopScheduledTask[task]],
    Button["remove", RemoveScheduledTask[task]; Clear[task]],
    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.

$\endgroup$
0
$\begingroup$

This functions

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

Update

Run a predefined task

Module[{i = 0, t1},
 t1 = CreateScheduledTask[++i, 0.1];
 Row[{
   Button["Run  t1", StartScheduledTask[t1]], " ",
   Button["Stop t1", StopScheduledTask[t1]], " ",
   Button["Reset  ", i = 0], " ",
   Dynamic@i}]]

I didn't find a way to make this run inside a DynamicModule.

$\endgroup$
  • 1
    $\begingroup$ 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].... $\endgroup$ – michelson Jan 4 '16 at 18:50
  • 2
    $\begingroup$ 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. $\endgroup$ – Kuba Jan 5 '16 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.