:- dynamic 	scheduled/3.   % Tag goes first for indexing

schedule_in(Rel, Goal, Tag) :-
	get_time(Now),
	Time is Now + Rel,
	schedule_at(Time, Goal, Tag).

schedule_at(Time, Goal, Tag) :-
	(   var(Tag)
	->  gensym(schedule_record_, Tag)
	;   true
	),
	assert(scheduled(Tag, Time, Goal)).

unschedule(Time, Goal, Tag) :-
	retractall(scheduled(Tag, Time, Goal)), !.
unschedule(_Time, _Goal, _Tag) :-
	throw(wtf).

start_scheduled_goal_caller :-
	thread_create(scheduled_goal_caller, _, [alias(schedule)]).

scheduled_goal_caller :-
	repeat,
	sleep(0.005),   % causes immeassurably small cpu usage ( < 0.01% )
	get_time(Now),
	forall((   scheduled(Tag, Time, Goal),
		   Now > Time
	       ),
	       (
		 % thread_set_state(calling(Goal), Tag)
		 ( call(Goal) ; true ), 
		 retract(scheduled(Tag, Time, Goal))
	       )),
	fail.

% two same recs; only one gets called
%    use forall?