timer-deque-rs 0.5.2

A OS based timer and timer queue which implements timeout queues of different types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
# timer-deque-rs

<img src="https://cdn.4neko.org/timer_deque_rs.webp" width="350"/>

## Description
A OS based timer and timer event dequeue which can be used to create a simple timeout scheduling. Can be used just as OS timer or use it together with the
timeout deque.

This crate is still incomplete and not properly tested. The proof of concept is now developed.

<details>
  <summary>Policy</summary>

<img src="https://cdn.4neko.org/source_avail.webp" width="300"/>

- This crate i.e code is NOT an Open Source software. This is a FREE (gratis) software and follows the principle of Sources Available/Disclosed software which should be fairly used.
- It is published under FSF/OSI approved licenses however author does not follow/share/respect OSI and FSF principles and phylosophy. 
- License is subject to be changed in further versions without warning.
- If you are using code in non-free (in terms of gratis) software you MUST NEVER demand a development of any features which are missing and needed for your business if you are not sponsoring/contributing those changes.
- Access to the code can be limited by author to specific entities due to the local laws (not my bad or fault)(despite what is said in the license).

</details>

<details>
  <summary>AI policy</summary>

- AI generated sloppy code is prohibited. AI generates slop "a priori" (anyway).
- Licenses (thank you OSS sectarians ) do not anyhow limit AI training, but f^ck you all - ChatGPT, Co~~ck~~Pilot, especially Claude and rest unidentified cr@p.
- It is strongly discouraged from using the AI based tools to write or enhance the code. AI slope would 100% violate the license by introducing the 3rd party licensed code.

</details>  

<details>
  <summary>Pull requests</summary>

  The pull requests are now supported because the repository was moved to Codeberg. The alternative way is to send patches 
  over the email to patch\[at\]4neko.org.

  In case if you would like to contribute the code, please use pull request. Your pull request should include:
- Description of changes and why it is needed.
- Test the pull request.

  In case of you prefer email and patch files please consider the following:
- For each feature or fix, please send patches separatly.
- Please write what your patch is implementing or fixing.
- I can read the code and I am able to understand it, so don't write a poem or essay in the description to the patches.
- Please test your patch.

</details> 

<details>
  <summary>Questions about license MPL-2.0</summary>

- Can I use the MPL-2.0 licensed code (crate) in larger project licensed with more permissive license like BSD or MIT.

>  Yes, MPL- and Apache-licensed code can be used with an MIT codebase (so in that sense, they are "compatible").
However, the MPL- / Apache-licensed code remains under its original license. (So although compatible, you cannot relicense someone else's MPL or Apache code into the MIT license.) This means that your final codebase will contain a mix of MPL, Apache, and MIT licensed code.
As an example, MPL has weak copyleft, so if you modified an MPL file, that file (including your changes) must remain under the MPL license. 

[Answer1](https://www.reddit.com/r/learnprogramming/comments/1dn58or/comment/la0jt4c/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button)

>I want to distribute (outside my organization) executable programs or libraries that I have compiled from someone else's unchanged MPL-licensed source code, either standalone or part of a larger work. What do I have to do?

>You must inform the recipients where they can get the source for the MPLed code in the executable program or library you are distributing (i.e., you must comply with Section 3.2). You may distribute any executables you create under a license of your choosing, as long as that license does not interfere with the recipients' rights to the source under the terms of the MPL.

[MPL2.0 FAQ](https://www.mozilla.org/en-US/MPL/2.0/FAQ/)

</details>  

<details>
  <summary>Questions about license EUPL-1.2</summary>

You should use this license if you are located in the EU which gives you more advantages over GPL because
in case of any disputes, the license allows you to defend your rights in a European Union country, in this case it will be Spain. It has also been translated into all languages of the EU member states.

[Matrix of EUPL compatible open source licences](https://interoperable-europe.ec.europa.eu/collection/eupl/matrix-eupl-compatible-open-source-licences)

`EUPL-1.2` is incompatiable with `GPL` according to [GNU ORG](https://www.gnu.org/licenses/license-list.html)

> This is a free software license. By itself, it has a copyleft comparable to the GPL's, and incompatible with it.

</details>

## Version  
v 0.5.2-development, Rust edition 2024

<details>
  <summary>Changelog</summary>

Changes in the `timer_portable`.

- Fixed compilation error (removed ICoW dep by acident from Cargo.toml)
- Updated test.

</details>

<details>
  <summary>Changelog v0.5.1</summary>

Changes in the `timer_portable`.

- Fixed periodic timer `timer_kqueue_fd_bsd.rs`.
- Fixed Tokio Async fd error. The `AsyncFd::with_interest` should be used instead of `AsyncFd::new`.
- The `ICoW` was replaces with a beter option `AtomicCell` for this particular case.

</details>

<details>
  <summary>Changelog v0.5.0</summary>

Changes in the `timer_portable`.

- A BSD (timers) experimental support was introduced with a patch which is in `master` of the git before the crate release.
It inclused a both `KQueue` and `timerfd` (Linux compat) based `timer` and `poll`. Features `bsd_use_timerfd` and `bsd_use_poll`
enbales a specific subsystems. `bsd_use_poll` switches from `KQueue` to `Poll`, `bsd_use_timerfd` switches from `KQueue` to `TimerFd`.
- Changes in the `poll` and `timer` interfaces.

### Important

A tokio's AsyncFd throws error when trying to use it on all KQueue, timerfd, poll. The reason is unknown. Probably this is due regresson or because all three are read-only.

</details>

<details>
  <summary>Changelog v0.4.0</summary>

Changes in the `layout`, `poll system` and `tasks`. 

- A `poll` now provides an option to interrupt the polling process from another thread. Also, polling can be interrupted by adding or removing timer.
- Added a simple task spawner and executor based on the parallel execution.
</details>

<details>
  <summary>Changelog v0.3.0</summary>

Changes in the `layout`, `time types` and `new deque modes`. 

- A layout of the crate's files was changed. The deque based on timeouts are now in directory deque_timeout.
- A new time types were introduced which would allow to perform the manipulations on the time: `AbsoluteTime` and `RelativeTime`. Both
are also a types which modifies the behaviour of the code.
- A new deque modes were introduced: `OrderdTimerDequeOnce` and `OrderdTimerDequePeriodic`. Both are based
on `AbsoluteTime` however the latter using `RelativeTime` time to offset the next timeout. The difference is: the former removes the item from the queue after timeout, the latter keeps it until manually removed.
</details>

<details>
  <summary>Changelog v0.2.0</summary>

Changes in the `poll` system. 

- Now, only structures marked as `AsTimerFd` can be added to instance.
- Now, timers are binded to the `polling` instance by the weak reference. If timer drops, it will be 
automatically removed from the `poll`.
- New tests added.
</details>

## License:

<img src="https://cdn.4neko.org/mpl_or_eupl_500.webp" width="300"/>

Sources are available under: MPL-2.0 OR EUPL-1.2 

## Supports:  
- GNU/Linux.
- Three dequeue types with the scheduling using absolute time.
- Synchronious (parallel) task spawner and executor.
- Async
- FreeBSD (experimental)

## ToDo
- other BSD based systems (kqueue) i.e (OSX, OpenBSD, NetBSD, DragonflyBSD)
- other timers types and queues i.e async task

## Does not support:
- Windows
- no_std

## Issues tracker:
<img src="https://cdn.4neko.org/move_codeberg_500.webp" width="200"/>

The project has moved to [Codeberg](https://codeberg.org/4neko/timer-deque-rs).

## Features

### Below is related to BSD systems
- `bsd_use_timerfd` - use `timerfd` instead of `kqueue`
- `bsd_use_poll` - use `poll` instread of `kqueue`

## Usage:  

see ./examples/ [there](https://codeberg.org/4neko/timer-deque-rs/src/branch/master/examples)

## Diagrams

### OrderdTimerDequeOnce operation mode

<details>
  <summary>Diagram</summary>

```
          ┌────────────────────────────┐                                
          │                            │                                
          │   OrderdTimerDequeOnce     │                                
          │                            │                                
          └────────────────────────────┘                                
┌─────────────────────────────┐           ┌────────────────────────────┐
│       Deque                 │           │        TimerFD             │
│                             │           │                            │
│                             │           │  timeout: 12332456         │
│   ┌─────────────────────┐   │           │      absoute time          │
│   │  ITEM               │   │           └───────────┬────────────────┘
│   │  TIMEOUT: 12332456  │ ──┼──────┐                │                 
│   └─────────────────────┘   │      │      ──────────┼─────────────    
│                             │      │                │                 
│                             │      │                ▼                 
│   ┌─────────────────────┐   │      │      ┌────────────────────┐      
│   │  ITEM               │   │      │      │                    │      
│   │  TIMOEUT: 12334543  ┼───┼────┐ │      │     timeout        │      
│   └─────────────────────┘   │    │ │      └─────────┬──────────┘      
│                             │    │ │                │                 
│                             │    │ │                │                 
│   ┌─────────────────────┐   │    │ │                ▼                 
│   │  ITEM               │   │    │ │      ┌────────────────────┐      
│   │  TIMEOUT: 12335654  │   │    │ │      │                    │      
│   └─────────────────────┘   │    │ └────► │      pop_front     │      
│                             │    │        │  timeout <= cur_tm │      
│                             │    │        └─────────┬──────────┘      
│       ............          │    │                  │                 
│                             │    │                  │                 
│                             │    │                  │                 
└─────────────────────────────┘    │                  ▼                 
                                   │        ┌──────────────────┐        
                                   │        │                  │        
                                   └───────►│    set_timer     │        
                                            │                  │        
                                            └─────────┬────────┘        
                                        ┌─────────────▼──────────────┐  
                                        │        TimerFD             │  
                                        │                            │  
                                        │  timeout: 12334543         │  
                                        │      absoute time          │  
                                        └──────────┬─────────────────┘  
                                           ┌───────▼────────────┐       
                                           │                    │       
                                           │     timeout        │       
                                           └─────────┬──────────┘       
```

</details>

### OrderdTimerDequeuPeriodic operation mode

<details>
  <summary>Diagram</summary>

```
                 ┌─────────────────────────────┐                                
                 │                             │                                
                 │   OrderdTimerDequeuPeriodic │                                
                 │                             │                                
                 └─────────────────────────────┘                                
       ┌─────────────────────────────┐           ┌────────────────────────────┐ 
       │       Deque                 │           │        TimerFD             │ 
       │                             │           │                            │ 
       │                             │           │  timeout: 12332456         │ 
       │   ┌─────────────────────┐   │           │      absoute time          │ 
       │   │  ITEM               │   │             ──────────┬────────────────┘ 
       │   │  TIMEOUT: 12332456  │ ──┼───────┐               │                  
       │   │  EXTEND: 100        │   │       │     ──────────┼─────────────     
       │   └─────────────────────┘   │       │               │                  
       │                             │       │               ▼                  
       │   ┌─────────────────────┐   │       │     ┌────────────────────┐       
       │   │  ITEM               │   │       │     │                    │       
       │   │  TIMOEUT: 12334543  ┼───┼────┐  │     │     timeout        │       
       │   │  EXTEND: 120        │   │    │  │     └─────────┬──────────┘       
       │   └─────────────────────┘   │    │  │               │                  
       │                             │    │  │               │                  
       │   ┌─────────────────────┐   │    │  │               ▼                  
       │   │  ITEM               │   │    │  │     ┌────────────────────┐       
       │   │  TIMEOUT: 12335654  │   │    │  │     │                    │       
       │   │  EXTEND: 150        │   │    │  └────►│      pop_front     │       
       │   └─────────────────────┘   │    │        │  timeout <= cur_tm │       
       │                             │    │        └─────────┬──────────┘       
┌──────┼───►   ............          │    │                  │                  
│      │                             │    │                  │                  
│      │                             │    │                  │                  
│      └─────────────────────────────┘    │                  ▼                  
│                                         │        ┌───────────────────────────┐
│                                         │        │  ITEM                     │
│              return back with new tm    │        │  TIMEOUT: 12332456+100    │
└─────────────────────────────────────────┼────────┼                           │
                                          │        │  NEW_TIMEOUT: 12332556    │
                                          │        └──────────┬────────────────┘
                                          │                   ▼                 
                                          │          ┌──────────────────┐       
                                          │          │                  │       
                                          │          │    set_timer     │       
                                          └─────────►│                  │       
                                                     └─────────┬────────┘       
                                                 ┌─────────────▼──────────────┐ 
                                                 │        TimerFD             │ 
                                                 │                            │ 
                                                 │  timeout: 12334543         │ 
                                                 │      absoute time          │ 
                                                 └──────────┬─────────────────┘ 
                                                    ┌───────▼────────────┐      
                                                    │                    │      
                                                    │     timeout        │      
                                                    └─────────┬──────────┘      
                                                                                
                                                         ...                    
```

</details>

The items are stored sorted by timeout `VecDeque`. The identification of the item in the queue is perfomed
by `PartialEq` and `Eq` by the instance or ID, and not by timeout value. The timer is set to the nearest (by time) value.

## Examples

For every sync example, the event notification is used. In case of Linux, the EPoll is used.

### Timer queue type consumer

This type of dequeue is consuming the instance.

<details>
  <summary>Example</summary>

```rust
use std::{cmp::Ordering, fmt, os::fd::{AsFd, AsRawFd, RawFd}, sync::Arc};

use timer_deque_rs::
{
    AbsoluteTime, 
    OrderdTimerDequeOnce, 
    OrderedTimerDeque, 
    TimerDequeueConsumer, 
    TimerPoll, 
    TimerReadRes
};

#[derive(Debug, PartialEq, Eq, Clone)]
struct TestItem(u64);

impl fmt::Display for TestItem
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "0 = {}", self.0)
    }
}

fn main()
{
    let ev_watch = TimerPoll::new().unwrap();

    let mut time_list = 
        OrderedTimerDeque
            ::<TimerDequeueConsumer<Arc<TestItem>, OrderdTimerDequeOnce>>
            ::new("test_label".into(), 4, false).unwrap();

    // add timer to event 
    ev_watch.add(&time_list).unwrap();

    let abs_time = AbsoluteTime::now();
    
    let tss_set1 = abs_time.clone().add_sec(3);
    let ent1 = Arc::new(TestItem(1));

    let tss_set2 = abs_time.clone().add_sec(7);
    let ent2 = Arc::new(TestItem(2));

    let tss_set3 = abs_time.clone().add_sec(10);
    let ent3 = Arc::new(TestItem(3));

    time_list.add_to_timer(ent1.clone(), tss_set1).unwrap();
    time_list.add_to_timer(ent2.clone(), tss_set2).unwrap();
    time_list.add_to_timer(ent3.clone(), tss_set3).unwrap();

    // poll timer for events (it can be done in separate thread)
    let res = ev_watch.poll(Option::None).unwrap();

    let poll_timeout = AbsoluteTime::now();

    assert_eq!(res.is_some(), true);
    assert_eq!(res.as_ref().unwrap().len(), 1);

    // get timer's FD's to identify which timers are ready
    let timer_fd: RawFd = res.as_ref().unwrap()[0];
    
    assert_eq!(timer_fd, time_list.as_fd().as_raw_fd());

    // consume event from timer to find out what happened
    let res = time_list.wait_for_event().unwrap();

    println!("timer timeout with result: {}", res);

    // it should be TimerReadRes::Ok with overflow 1
    assert_eq!(TimerReadRes::Ok(1), res);

    let mut timeout_items: Vec<Arc<TestItem>> = Vec::new();

    // read timeout items
    time_list.timeout_event_handler(res, &mut timeout_items).unwrap();


    assert_eq!(timeout_items.len(), 1); // only one item
    assert_eq!(timeout_items[0], ent1); // item 1

    println!("timer item: {}, timeout: {}, curtime: {}", &timeout_items[0], tss_set1, poll_timeout);
    assert_eq!(tss_set1.seconds_cmp(&poll_timeout) == Ordering::Equal, true);

    // removing second item from queue, so ent3 should be next to fire
    time_list.remove_from_sched_queue(&ent2).unwrap();

    assert_eq!(time_list.timer_queue_len(), 1); // only ent3 left

    println!("item {} removed from shed. queue", ent2);
    println!("queue len: {}", time_list.timer_queue_len());

    // -----
    // wait for events (ent3)
    let res = ev_watch.poll(Option::None).unwrap();

    let poll_timeout = AbsoluteTime::now();

    assert_eq!(res.is_some(), true);
    assert_eq!(res.as_ref().unwrap().len(), 1);

    // get timer's FD's to identify which timers are ready
    let timer_fd: RawFd = res.as_ref().unwrap()[0];
    
    assert_eq!(timer_fd, time_list.as_fd().as_raw_fd());

    // consume event from timer to find out what happened
    let res = time_list.wait_for_event().unwrap();

    println!("timer timeout with result: {}", res);

    // it should be TimerReadRes::Ok with overflow 1
    assert_eq!(TimerReadRes::Ok(1), res);

    let mut timeout_items: Vec<Arc<TestItem>> = Vec::new();

    time_list.timeout_event_handler(res, &mut timeout_items).unwrap();

    assert_eq!(timeout_items.len(), 1); // only one item
    assert_eq!(timeout_items[0], ent3); // item 3

    println!("timer item: {}, timeout: {}, curtime: {}", &timeout_items[0], tss_set3, poll_timeout);
    assert_eq!(tss_set3.seconds_cmp(&poll_timeout) == Ordering::Equal, true);

    println!("timer queue len: {}", time_list.timer_queue_len());

    assert_eq!(time_list.timer_queue_len(), 0); // queue should be empty

    return;
}
```
</details>


### Timer queue type ticket issuer

This type of dequeue is issuing the ticket for an instance which can be cancelled (ticket).

<details>
  <summary>Example</summary>

```rust
use std::{cmp::Ordering, fmt, os::fd::{AsFd, AsRawFd, RawFd}};

use timer_deque_rs::
{
    AbsoluteTime, 
    OrderdTimerDequeOnce, 
    OrderedTimerDeque, 
    TimerDequeueId, 
    TimerDequeueTicket, 
    TimerDequeueTicketIssuer, 
    TimerPoll, 
    TimerReadRes
};

#[derive(Debug, PartialEq, Eq)]
struct TestItem(TimerDequeueTicket);

impl fmt::Display for TestItem
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "0 = {}", self.0)
    }
}

fn main()
{
    let ev_watch = TimerPoll::new().unwrap();

    let mut time_list = 
        OrderedTimerDeque
            ::<TimerDequeueTicketIssuer<OrderdTimerDequeOnce>>
            ::new("test_label".into(), 4, false).unwrap();

    // add timer to event 
    ev_watch.add(&time_list).unwrap();


    let abs_time = AbsoluteTime::now();

    // add to timer
    let tss_set1 = abs_time.clone().add_sec(3);
    let ticket1 = time_list.add_to_timer(tss_set1).unwrap();
    let ent1 = TestItem(ticket1);

    let tss_set2 = abs_time.clone().add_sec(7);
    let ticket2 = time_list.add_to_timer(tss_set2).unwrap();
    let ent2 = TestItem(ticket2);

    let tss_set3 = abs_time.clone().add_sec(10);
    let ticket3 = time_list.add_to_timer(tss_set3).unwrap();
    let ent3 = TestItem(ticket3);

    // poll timer

    let res = ev_watch.poll(Option::None).unwrap();

    let poll_timeout = AbsoluteTime::now();

    assert_eq!(res.is_some(), true);
    assert_eq!(res.as_ref().unwrap().len(), 1);

    // get timer's FD's to identify which timers are ready
    let timer_fd: RawFd = res.as_ref().unwrap()[0];
    
    assert_eq!(timer_fd, time_list.as_fd().as_raw_fd());

    // consume event from timer to find out what happened
    let res = time_list.wait_for_event().unwrap();

    println!("timer timeout with result: {}", res);

    // it should be TimerReadRes::Ok with overflow 1
    assert_eq!(TimerReadRes::Ok(1), res);

    let mut timeout_items: Vec<TimerDequeueId> = Vec::new();

    // read timeout items
    time_list.timeout_event_handler(res, &mut timeout_items).unwrap();

    assert_eq!(timeout_items.len(), 1); // only one item
    assert_eq!(timeout_items[0], ent1.0); // item 1

    assert_eq!(ent1.0, timeout_items[0]);
    assert_eq!(ent1.0.is_queued(), false);

    println!("timer item: {}, timeout: {}, curtime: {}", &timeout_items[0], tss_set1, poll_timeout);
    assert_eq!(tss_set1.seconds_cmp(&poll_timeout) == Ordering::Equal, true);

    // removing second item from queue, so ent3 should be next to fire
    println!("item {} removing from shed. queue", ent2);

    time_list.remove_from_sched_queue(ent2.0).unwrap();

    assert_eq!(time_list.timer_queue_len(), 1); // only ent3 left
    println!("queue len: {}", time_list.timer_queue_len());

    // -----
    // wait for events (ent3)
    let res = ev_watch.poll(Option::None).unwrap();

    let poll_timeout = AbsoluteTime::now();

    assert_eq!(res.is_some(), true);
    assert_eq!(res.as_ref().unwrap().len(), 1);

    // get timer's FD's to identify which timers are ready
    let timer_fd: RawFd = res.as_ref().unwrap()[0];
    
    assert_eq!(timer_fd, time_list.as_fd().as_raw_fd());

    // consume event from timer to find out what happened
    let res = time_list.wait_for_event().unwrap();

    println!("timer timeout with result: {}", res);

    // it should be TimerReadRes::Ok with overflow 1
    assert_eq!(TimerReadRes::Ok(1), res);

    let mut timeout_items: Vec<TimerDequeueId> = Vec::new();

    time_list.timeout_event_handler(res, &mut timeout_items).unwrap();

    assert_eq!(timeout_items.len(), 1); // only one item
    assert_eq!(timeout_items[0], ent3.0); // item 3

    println!("timer item: {}, timeout: {}, curtime: {}", &timeout_items[0], tss_set3, poll_timeout);
    assert_eq!(tss_set3.seconds_cmp(&poll_timeout) == Ordering::Equal, true);

    println!("timer queue len: {}", time_list.timer_queue_len());

    assert_eq!(time_list.timer_queue_len(), 0); // queue should be empty

    return;
}
```
</details>

### Timer queue type notification (signal)

This type of dequeue is sending signal i.e notification using provided functionality.

<details>
  <summary>Example</summary>

```rust
use std::
{
    fmt, 
    os::fd::{AsFd, AsRawFd, RawFd}, 
    sync::{atomic::{AtomicBool, Ordering}, mpsc::{self, SendError}, Arc}, 
    time::Duration
};

use timer_deque_rs::
{
    common, 
    AbsoluteTime, 
    OrderdTimerDequeOnce, 
    OrderedTimerDeque, 
    TimerDequeueSignal, 
    TimerDequeueSignalTicket, 
    TimerPoll, 
    TimerReadRes
};


#[derive(Debug)]
pub struct TestStruct
{
    uniq_id: u64,
    sig_chan_snd: mpsc::Sender<u64>,
}

impl Eq for TestStruct {}

impl PartialEq for TestStruct
{
    fn eq(&self, other: &Self) -> bool 
    {
        return self.uniq_id == other.uniq_id;
    }
}

impl fmt::Display for TestStruct
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "uniq_id: {}", self.uniq_id)
    }
}

impl TimerDequeueSignal for TestStruct
{
    type TimerQueueID = u64;

    type TimeoutErr = SendError<Self::TimerQueueID>;

    fn get_id(&self) -> Self::TimerQueueID 
    {
        return self.uniq_id;
    }

    fn sig_timeout(&mut self) -> Result<(), Self::TimeoutErr> 
    {
        // non blocking
        return self.sig_chan_snd.send(self.uniq_id);
    }
}

impl TestStruct
{
    fn new(uniq_id: u64, snd: mpsc::Sender<u64>) -> Self
    {

        return Self{ uniq_id: uniq_id, sig_chan_snd: snd };
    }
}


fn main()
{
    let ev_watch = TimerPoll::new().unwrap();

    let mut time_list = 
        OrderedTimerDeque
            ::<TimerDequeueSignalTicket<TestStruct, OrderdTimerDequeOnce>>
            ::new("test_label".into(), 4, false).unwrap();

    // add timer to event 
    ev_watch.add(&time_list).unwrap();

    let (snd, rcv) = mpsc::channel::<u64>();
    let exit_flag = Arc::new(AtomicBool::new(false));
    let c_exit_flag = exit_flag.clone();

    let thread_hndlr = 
        std::thread::spawn(move ||
            {
                let mut exp_ids = vec![300, 100];
                loop
                {
                    let Ok(uniq_id) = rcv.recv_timeout(Duration::from_millis(100))
                        else 
                        { 
                            if c_exit_flag.load(Ordering::Relaxed) == true
                            {
                                return;
                            }
                            else if exp_ids.len() == 0
                            {
                                return;
                            }

                            continue;
                        };

                    println!("received timeout signal from item: {}", uniq_id);

                    assert_eq!(exp_ids.pop().unwrap(), uniq_id);
                }
            }
        );

    let abs_time = AbsoluteTime::now();

    let tss_set1 = abs_time.clone().add_sec(3);
    let ent1 = TestStruct::new(100, snd.clone());

    let tss_set2 = abs_time.clone().add_sec(7);
    let ent2 = TestStruct::new(200, snd.clone());

    let tss_set3 = abs_time.clone().add_sec(10);
    let ent3 = TestStruct::new(300, snd.clone());

    time_list.add_to_timer(ent1, tss_set1).unwrap();
    time_list.add_to_timer(ent2, tss_set2).unwrap();
    time_list.add_to_timer(ent3, tss_set3).unwrap();


    let res = ev_watch.poll(Option::None).unwrap();

    let poll_timeout = common::get_current_timestamp().timestamp();

    assert_eq!(res.is_some(), true);
    assert_eq!(res.as_ref().unwrap().len(), 1);

    // get timer's FD's to identify which timers are ready
    let timer_fd: RawFd = res.as_ref().unwrap()[0];
    
    assert_eq!(timer_fd, time_list.as_fd().as_raw_fd());

    // consume event from timer to find out what happened
    let res = time_list.wait_for_event().unwrap();

    println!("timer timeout with result: {},  timeout: {}, curtime: {}", res, tss_set1, poll_timeout);

    // it should be TimerReadRes::Ok with overflow 1
    assert_eq!(TimerReadRes::Ok(1), res);

    // read timeout items
    time_list.timeout_event_handler(res).unwrap();

    // removing second item from queue, so ent3 should be next to fire
    time_list.remove_from_sched_queue(&200).unwrap();


 // -----
    // wait for events (ent3)
    let res = ev_watch.poll(Option::None).unwrap();

    let poll_timeout = common::get_current_timestamp().timestamp();

    assert_eq!(res.is_some(), true);
    assert_eq!(res.as_ref().unwrap().len(), 1);

    // get timer's FD's to identify which timers are ready
    let timer_fd: RawFd = res.as_ref().unwrap()[0];
    
    assert_eq!(timer_fd, time_list.as_fd().as_raw_fd());

    // consume event from timer to find out what happened
    let res = time_list.wait_for_event().unwrap();

    println!("timer timeout with result: {},  timeout: {}, curtime: {}", res, tss_set3, poll_timeout);

    // it should be TimerReadRes::Ok with overflow 1
    assert_eq!(TimerReadRes::Ok(1), res);

    time_list.timeout_event_handler(res).unwrap();

    thread_hndlr.join().unwrap();

    return;
}
```
</details>


### Timer queue type consumer (async) polling future (less efficient)

In this example, the consumer type of deque is used in async context by polling the
timer. This is not efficient. In the next example, the AsyncFd is used it increase efficiency.

<details>
  <summary>Example</summary>

```rust
use std::{cmp::Ordering, fmt, sync::Arc};

use timer_deque_rs::
{
    AbsoluteTime, 
    OrderdTimerDequeOnce, 
    OrderedTimerDeque, 
    TimerDequeueConsumer, 
    TimerReadRes
};


#[derive(Debug, PartialEq, Eq, Clone)]
struct TestItem(u64);

impl fmt::Display for TestItem
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "0 = {}", self.0)
    }
}

#[tokio::main]
async fn main()
{
    let mut time_list = 
        OrderedTimerDeque
            ::<TimerDequeueConsumer<Arc<TestItem>, OrderdTimerDequeOnce>>
            ::new("test_label_async".into(), 4, false)
                .unwrap();

    let abs_time = AbsoluteTime::now();

    let tss_set1 = abs_time.clone().add_sec(3);
    let ent1 = Arc::new(TestItem(1));

    let tss_set2 = abs_time.clone().add_sec(7);
    let ent2 = Arc::new(TestItem(2));

    let tss_set3 = abs_time.clone().add_sec(10);
    let ent3 = Arc::new(TestItem(3));

    time_list.add_to_timer(ent1.clone(), tss_set1).unwrap();
    time_list.add_to_timer(ent2.clone(), tss_set2).unwrap();
    time_list.add_to_timer(ent3.clone(), tss_set3).unwrap();


    let res = time_list.poll().await.unwrap();

    let poll_timeout = AbsoluteTime::now();

    println!("timer timeout with result: {}", res);

    // it should be TimerReadRes::Ok with overflow 1
    assert_eq!(TimerReadRes::Ok(1), res);

    let mut timeout_items: Vec<Arc<TestItem>> = Vec::new();

    // read timeout items
    time_list.timeout_event_handler(res, &mut timeout_items).unwrap();

    assert_eq!(timeout_items.len(), 1); // only one item
    assert_eq!(timeout_items[0], ent1); // item 1

    println!("timer item: {}, timeout: {}, curtime: {}", &timeout_items[0], tss_set1, poll_timeout);
    assert_eq!(tss_set1.seconds_cmp(&poll_timeout) == Ordering::Equal, true);

    // removing second item from queue, so ent3 should be next to fire
    time_list.remove_from_sched_queue(&ent2).unwrap();

    assert_eq!(time_list.timer_queue_len(), 1); // only ent3 left

    println!("item {} removed from shed. queue", ent2);
    println!("queue len: {}", time_list.timer_queue_len());

    // -----
    // wait for events (ent3)

    // poll timer again for timeout
    let res = time_list.poll().await.unwrap();

    let poll_timeout = AbsoluteTime::now();

    println!("timer timeout with result: {}", res);

    // it should be TimerReadRes::Ok with overflow 1
    assert_eq!(TimerReadRes::Ok(1), res);

    let mut timeout_items: Vec<Arc<TestItem>> = Vec::new();

    time_list.timeout_event_handler(res, &mut timeout_items).unwrap();

    assert_eq!(timeout_items.len(), 1); // only one item
    assert_eq!(timeout_items[0], ent3); // item 3

    println!("timer item: {}, timeout: {}, curtime: {}", &timeout_items[0], tss_set3, poll_timeout);
    assert_eq!(tss_set3.seconds_cmp(&poll_timeout) == Ordering::Equal, true);

    println!("timer queue len: {}", time_list.timer_queue_len());

    assert_eq!(time_list.timer_queue_len(), 0); // queue should be empty

    return;
}
```
</details>

### Timer queue type notifier (async) using more efficient AsyncFd

In this example, the notifier (signal) type of deque is used in async context by wrapping the timer deque in
the AsyncFd. This is more efficient than jus polling the FD for events like in previous example.

<details>
  <summary>Example</summary>

```rust
use std::fmt;

use timer_deque_rs::
{
    common, 
    AbsoluteTime, 
    OrderdTimerDequeOnce, 
    OrderedTimerDeque, 
    TimerDequeueSignal, 
    TimerDequeueSignalTicket, 
    TimerReadRes
};

use tokio::
{
    io::{unix::AsyncFd, Interest}, 
    sync::mpsc::{self, error::SendError}
};


#[derive(Debug)]
pub struct TestStruct
{
    uniq_id: u64,
    sig_chan_snd: mpsc::UnboundedSender<u64>,
}

impl Eq for TestStruct {}

impl PartialEq for TestStruct
{
    fn eq(&self, other: &Self) -> bool 
    {
        return self.uniq_id == other.uniq_id;
    }
}

impl fmt::Display for TestStruct
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "uniq_id: {}", self.uniq_id)
    }
}

impl TimerDequeueSignal for TestStruct
{
    type TimerQueueID = u64;

    type TimeoutErr = SendError<Self::TimerQueueID>;

    fn get_id(&self) -> Self::TimerQueueID 
    {
        return self.uniq_id;
    }

    async 
    fn a_sig_timeout(&mut self) -> Result<(), Self::TimeoutErr> 
    {
        // non blocking
        return self.sig_chan_snd.send(self.uniq_id);
    }
}

impl TestStruct
{
    fn new(uniq_id: u64, snd: mpsc::UnboundedSender<u64>) -> Self
    {

        return Self{ uniq_id: uniq_id, sig_chan_snd: snd };
    }
}

#[tokio::main]
async fn main()
{
    let time_list = 
        OrderedTimerDeque
            ::<TimerDequeueSignalTicket<TestStruct, OrderdTimerDequeOnce>>
            ::new("test_label".into(), 4, false).unwrap();

    let mut async_time_list = 
        AsyncFd::with_interest(time_list, Interest::READABLE).unwrap();

    let (snd, mut rcv) = mpsc::unbounded_channel::<u64>();

    let hndl = 
        tokio::spawn(async move
            {
                let mut exp_ids = vec![300, 100];
                loop
                {
                    let Some(uniq_id) = rcv.recv().await
                        else 
                        { 
                            return;
                        };

                    println!("received timeout signal from item: {}", uniq_id);

                    assert_eq!(exp_ids.pop().unwrap(), uniq_id);

                    if exp_ids.len() == 0
                    {
                        return;
                    }
                }
            }
        );

    let abs_time = AbsoluteTime::now();

    let tss_set1 = abs_time.clone().add_sec(3);
    let ent1 = TestStruct::new(100, snd.clone());

    let tss_set2 = abs_time.clone().add_sec(7);
    let ent2 = TestStruct::new(200, snd.clone());

    let tss_set3 = abs_time.clone().add_sec(10);
    let ent3 = TestStruct::new(300, snd.clone());

    async_time_list.get_mut().add_to_timer(ent1, tss_set1).unwrap();
    async_time_list.get_mut().add_to_timer(ent2, tss_set2).unwrap();
    async_time_list.get_mut().add_to_timer(ent3, tss_set3).unwrap();

    // poll the timer until it becomes ready
    let mut read_guard = 
        async_time_list.ready_mut(Interest::READABLE).await.unwrap();

    // clear ready otherwise it will return WOULDBLOCK
    read_guard.clear_ready();
    
    let poll_timeout = common::get_current_timestamp().timestamp();

    let res = read_guard.get_inner().wait_for_event().unwrap();

    println!("timer timeout with result: {},  timeout: {}, curtime: {}", res, tss_set1, poll_timeout);

    assert_eq!(TimerReadRes::Ok(1), res);

    read_guard.get_inner_mut().async_timeout_event_handler(res).await.unwrap();

    // removing second item from queue, so ent3 should be next to fire
    async_time_list.get_mut().remove_from_sched_queue(&200).unwrap();


    // poll the timer until it becomes ready
    let mut read_guard = 
        async_time_list.ready_mut(Interest::READABLE).await.unwrap();
    
    let poll_timeout = common::get_current_timestamp().timestamp();

    let res = read_guard.get_inner().wait_for_event().unwrap();

    println!("timer timeout with result: {},  timeout: {}, curtime: {}", res, tss_set1, poll_timeout);

    assert_eq!(TimerReadRes::Ok(1), res);

    read_guard.get_inner_mut().async_timeout_event_handler(res).await.unwrap();


    let _ = hndl.await;

    return;
}
```
</details>

### Generic, OS based timer without queue

Just simple timer based on OS functionality.

<details>
  <summary>Example</summary>

```rust
use std::{borrow::Cow, cmp::Ordering, time::Instant};

use timer_deque_rs::
{
    timer_portable::
    {
        timer::TimerFd, 
        FdTimerCom, 
        TimerExpMode, 
        TimerFlags, 
        TimerType
    }, 
    AbsoluteTime
};

fn main()
{
    // timer init as blocking
    let timer = 
        TimerFd::new(Cow::Borrowed("test"), TimerType::CLOCK_REALTIME, 
            TimerFlags::empty()).unwrap();

    let s = Instant::now();

    let abs_time = AbsoluteTime::now().add_sec(3);
    let exp_time = 
         TimerExpMode::<AbsoluteTime>::new_oneshot(abs_time);

    // setting timer
    let res = timer.set_time(exp_time);
    
    println!("timer was set: '{}'", exp_time);

    assert_eq!(res.is_ok(), true, "{}", res.err().unwrap());

    
    let ovf = timer.read().unwrap().unwrap();

    let now_abs = AbsoluteTime::now();
    let e = s.elapsed();

    assert_eq!(ovf, 1);
    assert_eq!(abs_time.seconds_cmp(&now_abs) == Ordering::Equal, true);

    println!("elapsed: {:?}, now: {}, set: {}", e, now_abs, abs_time);

    assert_eq!((e.as_millis() <= 3100), true);

    println!("Success");
    return;
}

```
</details>

### A task spawn and executor

A simple parallel task spawner

<details>
  <summary>Example</summary>

```rust
    use std::{sync::mpsc::{self, RecvTimeoutError, Sender}, time::{Duration, Instant}};

    use crate::{periodic_task::sync_tasks::{PeriodicTask, PeriodicTaskResult, PeriodicTaskTime, SyncPeriodicTasks}, AbsoluteTime, RelativeTime};

    #[derive(Debug)]
    struct TaskStruct1
    {
        a1: u64,
        s: Sender<u64>,
    }

    impl TaskStruct1
    {
        fn new(a1: u64, s: Sender<u64>) -> Self
        {
            return Self{ a1: a1, s };
        }
    }

    impl PeriodicTask for TaskStruct1
    {
        fn exec(&mut self) -> PeriodicTaskResult
        {
            println!("taskstruct1 val: {}", self.a1);

            let _ = self.s.send(self.a1);

            return PeriodicTaskResult::Ok;
        }
    }

    fn main()
    {
        let s = SyncPeriodicTasks::new(1.try_into().unwrap()).unwrap();

        let (send, recv) = mpsc::channel::<u64>();

        let task1 = TaskStruct1::new(2, send);
        let task1_ptt = PeriodicTaskTime::exact_time(AbsoluteTime::now() + RelativeTime::new_time(3, 0));
        let task1_guard = s.add("task1", task1, task1_ptt).unwrap();

        println!("added");
        let val = recv.recv();

        println!("{:?}", val);

        drop(task1_guard);
    }
```
</details>