Based on your description I created the example below. You should be able to adapt it to your needs.
--*********************************************************************************
--* *
--* PROGRAM NAME : HBMonitor.kl *
--* CREATION DATE : *
--* DATE LAST MODIFIED : *
--* KAREL VERSION : *
--* WRITTEN BY : *
--* *
--*********************************************************************************
--*********************************************************************************
PROGRAM HBMonitor
%COMMENT = 'HBMonitor-V1.0'
%NOPAUSESHFT
%NOPAUSE = ERROR + TPENABLE + COMMAND
%NOLOCKGROUP
%NOBUSYLAMP
VAR
MONITOR: BOOLEAN
HEARTBEAT: BOOLEAN
--************************************************************
--**************************MAIN PROGRAM**************
--************************************************************
BEGIN
--HEARTBEAT = NOT DIN[100] --Digital input assumed to be false when you wish code to run, true to stop.
HEARTBEAT = DIN[100] --Digital input assumed to be true when you wish code to run, false to stop.
MONITOR = TRUE --The variable MONITOR keeps the program loop active until the heartbeat bit is true again. Set FALSE to abort
WHILE MONITOR DO
IF HEARTBEAT THEN
--CALL / RUN USER CODE HERE
ENDIF
DELAY 5 -- 5MS PAUSE TO AVOID FREEZING THE TP USER INTERFACE
ENDWHILE
END HBMonitor