cron_tab 0.2.13

A cron job library for Rust.
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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
//! Comprehensive asynchronous tests for CronTab
//!
//! This module contains all tests for the asynchronous functionality of the cron scheduler,
//! including basic async operations, comprehensive scheduling scenarios, error handling,
//! and performance validation in async contexts.

#![cfg(feature = "async")]

use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::collections::HashMap;

use chrono::{FixedOffset, Local, TimeZone, Utc, Timelike};
use cron_tab::AsyncCron;
use tokio::time::sleep;
use tokio::sync::Mutex;
use futures::future::join_all;

#[cfg(test)]
mod tests {
    use super::*;

    // ONE-TIME EXECUTION TESTS

    #[tokio::test]
    async fn test_add_fn_once() {
        let mut cron = AsyncCron::new(Utc);

        let counter = Arc::new(Mutex::new(0));
        let counter_clone = Arc::clone(&counter);

        // Schedule a one-time job 2 seconds in the future
        let target_time = Utc::now() + chrono::Duration::seconds(2);
        cron.add_fn_once(target_time, move || {
            let counter = Arc::clone(&counter_clone);
            async move {
                let mut value = counter.lock().await;
                *value += 1;
            }
        })
        .await
        .unwrap();

        cron.start().await;

        // Wait before the job should execute
        sleep(Duration::from_millis(1500)).await;
        assert_eq!(*counter.lock().await, 0, "Job should not have executed yet");

        // Wait for the job to execute
        sleep(Duration::from_millis(1000)).await;
        assert_eq!(*counter.lock().await, 1, "Job should have executed once");

        // Wait longer to ensure it doesn't execute again
        sleep(Duration::from_millis(2000)).await;
        assert_eq!(*counter.lock().await, 1, "Job should only execute once");

        cron.stop().await;
    }

    #[tokio::test]
    async fn test_add_fn_after() {
        let mut cron = AsyncCron::new(Utc);

        let counter = Arc::new(Mutex::new(0));
        let counter_clone = Arc::clone(&counter);

        // Schedule a job to run after 2 seconds
        cron.add_fn_after(Duration::from_secs(2), move || {
            let counter = Arc::clone(&counter_clone);
            async move {
                let mut value = counter.lock().await;
                *value += 1;
            }
        })
        .await
        .unwrap();

        cron.start().await;

        // Wait before the job should execute
        sleep(Duration::from_millis(1500)).await;
        assert_eq!(*counter.lock().await, 0, "Job should not have executed yet");

        // Wait for the job to execute (add extra time for async overhead)
        sleep(Duration::from_millis(1500)).await;
        assert_eq!(*counter.lock().await, 1, "Job should have executed once");

        // Wait longer to ensure it doesn't execute again
        sleep(Duration::from_millis(1500)).await;
        assert_eq!(*counter.lock().await, 1, "Job should only execute once");

        cron.stop().await;
    }

    #[tokio::test]
    async fn test_multiple_one_time_jobs() {
        let mut cron = AsyncCron::new(Utc);

        let counter = Arc::new(Mutex::new(0));
        let counter1 = Arc::clone(&counter);
        let counter2 = Arc::clone(&counter);
        let counter3 = Arc::clone(&counter);

        // Schedule multiple one-time jobs at different times
        cron.add_fn_after(Duration::from_secs(1), move || {
            let counter = Arc::clone(&counter1);
            async move {
                let mut value = counter.lock().await;
                *value += 1;
            }
        })
        .await
        .unwrap();

        cron.add_fn_after(Duration::from_secs(2), move || {
            let counter = Arc::clone(&counter2);
            async move {
                let mut value = counter.lock().await;
                *value += 10;
            }
        })
        .await
        .unwrap();

        cron.add_fn_after(Duration::from_secs(4), move || {
            let counter = Arc::clone(&counter3);
            async move {
                let mut value = counter.lock().await;
                *value += 100;
            }
        })
        .await
        .unwrap();

        cron.start().await;

        sleep(Duration::from_millis(1500)).await;
        assert_eq!(*counter.lock().await, 1, "First job should have executed");

        sleep(Duration::from_millis(1500)).await;
        assert_eq!(*counter.lock().await, 11, "Second job should have executed");

        sleep(Duration::from_millis(2500)).await;
        assert_eq!(*counter.lock().await, 111, "Third job should have executed");

        // Wait to ensure no more executions
        sleep(Duration::from_millis(1000)).await;
        assert_eq!(*counter.lock().await, 111, "No more jobs should execute");

        cron.stop().await;
    }

    #[tokio::test]
    async fn test_remove_one_time_job_before_execution() {
        let mut cron = AsyncCron::new(Utc);

        let counter = Arc::new(Mutex::new(0));
        let counter_clone = Arc::clone(&counter);

        // Schedule a one-time job
        let job_id = cron
            .add_fn_after(Duration::from_secs(2), move || {
                let counter = Arc::clone(&counter_clone);
                async move {
                    let mut value = counter.lock().await;
                    *value += 1;
                }
            })
            .await
            .unwrap();

        cron.start().await;

        // Remove the job before it executes
        sleep(Duration::from_millis(500)).await;
        cron.remove(job_id).await;

        // Wait past when the job would have executed
        sleep(Duration::from_millis(2000)).await;
        assert_eq!(*counter.lock().await, 0, "Removed job should not execute");

        cron.stop().await;
    }

    #[tokio::test]
    async fn test_mix_recurring_and_one_time_jobs() {
        let mut cron = AsyncCron::new(Utc);

        let recurring_counter = Arc::new(Mutex::new(0));
        let recurring_counter_clone = Arc::clone(&recurring_counter);

        let once_counter = Arc::new(Mutex::new(0));
        let once_counter_clone = Arc::clone(&once_counter);

        // Add a recurring job that runs every second
        cron.add_fn("* * * * * * *", move || {
            let counter = Arc::clone(&recurring_counter_clone);
            async move {
                let mut value = counter.lock().await;
                *value += 1;
            }
        })
        .await
        .unwrap();

        // Add a one-time job that runs after 2 seconds
        cron.add_fn_after(Duration::from_secs(2), move || {
            let counter = Arc::clone(&once_counter_clone);
            async move {
                let mut value = counter.lock().await;
                *value += 1;
            }
        })
        .await
        .unwrap();

        cron.start().await;

        sleep(Duration::from_millis(3500)).await;

        let recurring_count = *recurring_counter.lock().await;
        let once_count = *once_counter.lock().await;

        // Recurring job should have executed multiple times
        assert!(
            recurring_count >= 2,
            "Recurring job should execute multiple times, got {}",
            recurring_count
        );

        // One-time job should have executed exactly once
        assert_eq!(once_count, 1, "One-time job should execute exactly once");

        cron.stop().await;
    }

    #[tokio::test]
    async fn test_duration_out_of_range_error() {
        let mut cron = AsyncCron::new(Utc);

        // Test with an extremely large duration that exceeds chrono's limit
        let very_long_time = Duration::from_secs(u64::MAX);
        let result = cron
            .add_fn_after(very_long_time, || async {
                println!("This should not execute");
            })
            .await;

        assert!(result.is_err(), "Should fail with DurationOutOfRange");
        match result {
            Err(cron_tab::CronError::DurationOutOfRange) => {
                // Success - correct error type
            }
            Err(e) => panic!("Expected DurationOutOfRange, got {:?}", e),
            Ok(_) => panic!("Should have returned an error"),
        }

        // Test with a reasonable duration (should succeed)
        let normal_duration = Duration::from_secs(10);
        let result = cron
            .add_fn_after(normal_duration, || async {
                println!("This will execute");
            })
            .await;

        assert!(result.is_ok(), "Should succeed with normal duration");
    }

    // BASIC ASYNC FUNCTIONALITY TESTS

    #[tokio::test]
    async fn start_and_stop_cron() {
        let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
        let mut cron = AsyncCron::new(local_tz);

        cron.start().await;
        sleep(Duration::from_millis(50)).await;
        cron.stop().await;
    }

    #[tokio::test]
    async fn add_job_before_start() {
        let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
        let mut cron = AsyncCron::new(local_tz);

        let counter = Arc::new(Mutex::new(0));
        let counter_clone = Arc::clone(&counter);

        let job_id = cron
            .add_fn("* * * * * * *", move || {
                let counter = Arc::clone(&counter_clone);
                async move {
                    let mut count = counter.lock().await;
                    *count += 1;
                }
            })
            .await
            .unwrap();

        cron.start().await;
        sleep(Duration::from_millis(1100)).await;
        cron.stop().await;

        let count = *counter.lock().await;
        assert!(count >= 1);

        // Clean up
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn add_job() {
        let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
        let mut cron = AsyncCron::new(local_tz);

        cron.start().await;

        let counter = Arc::new(Mutex::new(0));
        let counter_clone = Arc::clone(&counter);

        let job_id = cron
            .add_fn("* * * * * * *", move || {
                let counter = Arc::clone(&counter_clone);
                async move {
                    let mut count = counter.lock().await;
                    *count += 1;
                }
            })
            .await
            .unwrap();

        sleep(Duration::from_millis(1100)).await;
        cron.stop().await;

        let count = *counter.lock().await;
        assert!(count >= 1);

        // Clean up
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn add_multiple_jobs() {
        let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
        let mut cron = AsyncCron::new(local_tz);

        cron.start().await;

        let counter1 = Arc::new(Mutex::new(0));
        let counter1_clone = Arc::clone(&counter1);

        let counter2 = Arc::new(Mutex::new(0));
        let counter2_clone = Arc::clone(&counter2);

        let job_id1 = cron
            .add_fn("* * * * * * *", move || {
                let counter = Arc::clone(&counter1_clone);
                async move {
                    let mut count = counter.lock().await;
                    *count += 1;
                }
            })
            .await
            .unwrap();

        let job_id2 = cron
            .add_fn("* * * * * * *", move || {
                let counter = Arc::clone(&counter2_clone);
                async move {
                    let mut count = counter.lock().await;
                    *count += 1;
                }
            })
            .await
            .unwrap();

        sleep(Duration::from_millis(1100)).await;
        cron.stop().await;

        let count1 = *counter1.lock().await;
        let count2 = *counter2.lock().await;
        assert!(count1 >= 1);
        assert!(count2 >= 1);

        // Clean up
        cron.remove(job_id1).await;
        cron.remove(job_id2).await;
    }

    #[tokio::test]
    async fn remove_job() {
        let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
        let mut cron = AsyncCron::new(local_tz);

        cron.start().await;

        let counter = Arc::new(Mutex::new(0));
        let counter_clone = Arc::clone(&counter);

        let job_id = cron
            .add_fn("* * * * * * *", move || {
                let counter = Arc::clone(&counter_clone);
                async move {
                    let mut count = counter.lock().await;
                    *count += 1;
                }
            })
            .await
            .unwrap();

        sleep(Duration::from_millis(1100)).await;

        let count_before_removal = *counter.lock().await;
        assert!(count_before_removal >= 1);

        cron.remove(job_id).await;

        // Reset counter to test that job was actually removed
        {
            let mut count = counter.lock().await;
            *count = 0;
        }

        sleep(Duration::from_millis(1100)).await;
        cron.stop().await;

        let count_after_removal = *counter.lock().await;
        // After removal, counter should remain 0
        assert_eq!(count_after_removal, 0);
    }

    // COMPREHENSIVE ASYNC TESTS

    #[tokio::test]
    async fn test_multiple_concurrent_jobs() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;

        let job_count = 10;
        let execution_count = Arc::new(AtomicUsize::new(0));
        let mut job_ids = Vec::new();

        // Add multiple jobs that all execute every second
        for _ in 0..job_count {
            let count = execution_count.clone();
            let job_id = cron.add_fn("* * * * * * *", move || {
                let count = count.clone();
                async move {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            }).await.unwrap();
            job_ids.push(job_id);
        }

        // Let them run for a bit
        sleep(Duration::from_millis(1100)).await;
        
        cron.stop().await;

        let total_executions = execution_count.load(Ordering::SeqCst);
        // Should have at least job_count executions (1 for each job)
        assert!(total_executions >= job_count, "Expected at least {} executions, got {}", job_count, total_executions);

        // Clean up
        for job_id in job_ids {
            cron.remove(job_id).await;
        }
    }

    #[tokio::test]
    async fn test_rapid_job_manipulation() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;

        let mut job_ids = Vec::new();

        // Rapidly add many jobs
        for i in 0..50 {
            let job_id = cron.add_fn("* * * * * * *", move || {
                let _job_num = i;
                async move {
                    // Short delay to simulate work
                    tokio::time::sleep(Duration::from_millis(1)).await;
                }
            }).await.unwrap();
            job_ids.push(job_id);
        }

        // Rapidly remove some jobs
        for &job_id in job_ids.iter().take(25) {
            cron.remove(job_id).await;
        }

        // Add more jobs
        for i in 50..75 {
            let job_id = cron.add_fn("*/2 * * * * * *", move || {
                let _job_num = i;
                async move {
                    tokio::time::sleep(Duration::from_millis(1)).await;
                }
            }).await.unwrap();
            job_ids.push(job_id);
        }

        sleep(Duration::from_millis(500)).await;
        cron.stop().await;

        // Clean up remaining jobs
        for &job_id in job_ids.iter().skip(25) {
            cron.remove(job_id).await;
        }
    }

    #[tokio::test]
    async fn test_scheduler_precision_under_load() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;

        let execution_times = Arc::new(Mutex::new(Vec::new()));
        let times = Arc::clone(&execution_times);

        // Add a job that records execution times
        let job_id = cron.add_fn("* * * * * * *", move || {
            let times = Arc::clone(&times);
            async move {
                let now = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_millis();
                times.lock().await.push(now);
            }
        }).await.unwrap();

        // Add some load with other jobs
        let mut load_job_ids = Vec::new();
        for i in 0..10 {
            let load_job_id = cron.add_fn("*/2 * * * * * *", move || {
                let _job_num = i;
                async move {
                    // Simulate CPU work
                    tokio::time::sleep(Duration::from_millis(10)).await;
                }
            }).await.unwrap();
            load_job_ids.push(load_job_id);
        }

        sleep(Duration::from_millis(3100)).await;
        cron.stop().await;

        let times = execution_times.lock().await;
        assert!(times.len() >= 2, "Should have multiple executions");

        // Check that executions are roughly 1 second apart (within 500ms tolerance for high load)
        for window in times.windows(2) {
            let diff = window[1] - window[0];
            assert!(diff >= 500 && diff <= 1500, "Execution interval should be ~1000ms (+/-500ms), got {}ms", diff);
        }

        // Clean up
        cron.remove(job_id).await;
        for job_id in load_job_ids {
            cron.remove(job_id).await;
        }
    }

    #[tokio::test]
    async fn test_timezone_handling() {
        let offset = FixedOffset::east_opt(5 * 3600).unwrap(); // UTC+5
        let mut cron = AsyncCron::new(offset);
        cron.start().await;

        let execution_count = Arc::new(AtomicUsize::new(0));
        let count = Arc::clone(&execution_count);

        let job_id = cron.add_fn("0 * * * * * *", move || {
            let count = count.clone();
            async move {
                count.fetch_add(1, Ordering::SeqCst);
            }
        }).await.unwrap();

        // Run for a short time - job should execute at top of minute in the specified timezone
        sleep(Duration::from_millis(2000)).await;
        cron.stop().await;

        // Clean up
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_job_removal_during_execution() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;

        let execution_count = Arc::new(AtomicUsize::new(0));
        let long_running_flag = Arc::new(AtomicBool::new(false));

        let count = Arc::clone(&execution_count);
        let flag = Arc::clone(&long_running_flag);

        let job_id = cron.add_fn("* * * * * * *", move || {
            let count = count.clone();
            let flag = flag.clone();
            async move {
                flag.store(true, Ordering::SeqCst);
                tokio::time::sleep(Duration::from_millis(500)).await; // Long-running task
                count.fetch_add(1, Ordering::SeqCst);
                flag.store(false, Ordering::SeqCst);
            }
        }).await.unwrap();

        // Wait longer for job to start executing
        sleep(Duration::from_millis(1200)).await;

        // Remove job while it might be executing
        cron.remove(job_id).await;

        // Wait a bit more
        sleep(Duration::from_millis(1000)).await;
        cron.stop().await;

        let count = execution_count.load(Ordering::SeqCst);
        // Job should have executed at least once, but be more lenient with timing
        assert!(count >= 1 || long_running_flag.load(Ordering::SeqCst), 
               "Job should have executed or be in progress, count: {}, flag: {}", 
               count, long_running_flag.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn test_scheduler_restart() {
        let mut cron = AsyncCron::new(Utc);
        let execution_count = Arc::new(Mutex::new(0));
        let counter = Arc::clone(&execution_count);

        let job_id = cron.add_fn("* * * * * * *", move || {
            let counter = Arc::clone(&counter);
            async move {
                let mut count = counter.lock().await;
                *count += 1;
            }
        }).await.unwrap();

        // First run cycle
        cron.start().await;
        sleep(Duration::from_millis(1100)).await;
        cron.stop().await;

        let count_after_first_run = *execution_count.lock().await;
        assert!(count_after_first_run >= 1, "Should execute during first run");

        // Second run cycle
        cron.start().await;
        sleep(Duration::from_millis(1100)).await;
        cron.stop().await;

        let final_count = *execution_count.lock().await;
        assert!(final_count > count_after_first_run, "Should continue executing after restart");

        // Clean up
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_memory_stability_long_running() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;

        let execution_count = Arc::new(Mutex::new(0));
        let counter = Arc::clone(&execution_count);

        let job_id = cron.add_fn("* * * * * * *", move || {
            let counter = Arc::clone(&counter);
            async move {
                let mut count = counter.lock().await;
                *count += 1;
            }
        }).await.unwrap();

        // Run for longer period to test memory stability
        sleep(Duration::from_millis(5100)).await;
        cron.stop().await;

        let final_count = *execution_count.lock().await;
        assert!(final_count >= 4, "Should execute multiple times during long run, got {}", final_count);

        // Clean up
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_concurrent_cron_instances() {
        let instances = 5;
        let mut cron_instances = Vec::new();
        let mut counters = Vec::new();

        // Create multiple cron instances
        for _i in 0..instances {
            let mut cron = AsyncCron::new(Utc);
            let counter = Arc::new(Mutex::new(0));
            let counter_clone = Arc::clone(&counter);

            let _job_id = cron.add_fn("* * * * * * *", move || {
                let counter = counter_clone.clone();
                async move {
                    let mut count = counter.lock().await;
                    *count += 1;
                }
            }).await.unwrap();

            cron.start().await;
            cron_instances.push(cron);
            counters.push(counter);
        }

        sleep(Duration::from_millis(2100)).await;

        // Stop all instances
        for cron in &mut cron_instances {
            cron.stop().await;
        }

        // Verify all instances worked
        for (i, counter) in counters.iter().enumerate() {
            let count = *counter.lock().await;
            assert!(count >= 1, "Instance {} should have executed at least once, got {}", i, count);
        }
    }

    #[tokio::test]
    async fn test_complex_cron_expressions() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;

        let expression_results = Arc::new(Mutex::new(HashMap::new()));

        // Test various cron expressions
        let expressions = vec![
            ("* * * * * * *", "every_second"),
            ("*/2 * * * * * *", "every_2_seconds"),
            ("*/3 * * * * * *", "every_3_seconds"),
        ];

        let mut job_ids = Vec::new();
        for (expr, name) in expressions {
            let results = Arc::clone(&expression_results);
            let job_name = name.to_string();
            let job_id = cron.add_fn(expr, move || {
                let results = results.clone();
                let name = job_name.clone();
                async move {
                    let mut map = results.lock().await;
                    *map.entry(name).or_insert(0) += 1;
                }
            }).await.unwrap();
            job_ids.push(job_id);
        }

        sleep(Duration::from_millis(6100)).await;
        cron.stop().await;

        let results = expression_results.lock().await;
        assert!(results.get("every_second").unwrap_or(&0) >= &5, "Every second job should execute multiple times");
        assert!(results.get("every_2_seconds").unwrap_or(&0) >= &2, "Every 2 seconds job should execute");
        assert!(results.get("every_3_seconds").unwrap_or(&0) >= &1, "Every 3 seconds job should execute");

        // Clean up
        for job_id in job_ids {
            cron.remove(job_id).await;
        }
    }

    #[tokio::test]
    async fn test_job_execution_timing_precision() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;

        let execution_times = Arc::new(Mutex::new(Vec::new()));
        let times = Arc::clone(&execution_times);

        let job_id = cron.add_fn("* * * * * * *", move || {
            let times = times.clone();
            async move {
                let now = Instant::now();
                times.lock().await.push(now);
            }
        }).await.unwrap();

        sleep(Duration::from_millis(3100)).await;
        cron.stop().await;

        let times = execution_times.lock().await;
        assert!(times.len() >= 2, "Should have multiple execution times");

        // Check timing precision (should be roughly 1 second apart)
        for window in times.windows(2) {
            let diff = window[1].duration_since(window[0]);
            assert!(diff.as_millis() >= 900 && diff.as_millis() <= 1100, 
                   "Execution intervals should be ~1000ms, got {}ms", diff.as_millis());
        }

        // Clean up
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_error_recovery() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;

        let success_count = Arc::new(Mutex::new(0));
        let error_count = Arc::new(Mutex::new(0));

        let success_counter = Arc::clone(&success_count);
        let error_counter = Arc::clone(&error_count);

        let mut job_ids = Vec::new();

        // Add a job that sometimes panics
        let job_id1 = cron.add_fn("* * * * * * *", move || {
            let success = success_counter.clone();
            let errors = error_counter.clone();
            async move {
                let should_panic = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_millis() % 3 == 0;

                if should_panic {
                    let mut err_count = errors.lock().await;
                    *err_count += 1;
                    panic!("Simulated panic");
                } else {
                    let mut succ_count = success.lock().await;
                    *succ_count += 1;
                }
            }
        }).await.unwrap();
        job_ids.push(job_id1);

        // Add a normal job to ensure scheduler continues working
        let success_counter2 = Arc::clone(&success_count);
        let job_id2 = cron.add_fn("*/2 * * * * * *", move || {
            let success = success_counter2.clone();
            async move {
                let mut count = success.lock().await;
                *count += 1;
            }
        }).await.unwrap();
        job_ids.push(job_id2);

        sleep(Duration::from_millis(3100)).await;
        cron.stop().await;

        let success = *success_count.lock().await;
        assert!(success >= 1, "Should have some successful executions despite panics");

        // Clean up
        for job_id in job_ids {
            cron.remove(job_id).await;
        }
    }

    // ASYNC PERFORMANCE TESTS

    #[tokio::test]
    async fn test_async_concurrent_operations() {
        let num_crons = 3;
        let mut futures = vec![];

        for _i in 0..num_crons {
            let future = tokio::spawn(async move {
                let mut cron = AsyncCron::new(Utc);
                cron.start().await;

                let counter = Arc::new(Mutex::new(0));
                let counter_clone = Arc::clone(&counter);

                let job_id = cron.add_fn("* * * * * * *", move || {
                    let counter = counter_clone.clone();
                    async move {
                        let mut count = counter.lock().await;
                        *count += 1;
                    }
                }).await.unwrap();

                sleep(Duration::from_millis(1100)).await;
                cron.stop().await;

                let final_count = *counter.lock().await;
                cron.remove(job_id).await;
                final_count
            });
            futures.push(future);
        }

        let results = join_all(futures).await;

        for (i, result) in results.iter().enumerate() {
            let count = result.as_ref().unwrap();
            assert!(*count >= 1, "Cron instance {} should execute at least once, got {}", i, count);
        }
    }

    #[tokio::test] 
    async fn test_scheduler_overhead_async() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;

        let execution_times = Arc::new(Mutex::new(Vec::new()));
        let times = Arc::clone(&execution_times);

        let job_id = cron.add_fn("* * * * * * *", move || {
            let times = times.clone();
            async move {
                let now = Instant::now();
                times.lock().await.push(now);
            }
        }).await.unwrap();

        // Let it run for several executions
        sleep(Duration::from_millis(3100)).await;
        cron.stop().await;
        
        let times = execution_times.lock().await;
        assert!(times.len() >= 2, "Should have multiple executions for overhead test");
        
        // Verify overhead is minimal (timing should be consistent)
        for window in times.windows(2) {
            let interval = window[1].duration_since(window[0]);
            // Allow reasonable variance for async overhead and system load
            assert!(interval >= Duration::from_millis(500) && interval <= Duration::from_millis(1500),
                   "Async overhead should keep intervals close to 1000ms (+/-500ms), got {:?}", interval);
        }

        // Clean up
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_rapid_start_stop_cycles_async() {
        let mut cron = AsyncCron::new(Utc);
        
        let counter = Arc::new(Mutex::new(0));
        let counter_clone = Arc::clone(&counter);

        let job_id = cron.add_fn("* * * * * * *", move || {
            let counter = counter_clone.clone();
            async move {
                let mut count = counter.lock().await;
                *count += 1;
            }
        }).await.unwrap();

        // Rapidly start and stop the cron scheduler
        for _ in 0..20 {
            cron.start().await;
            sleep(Duration::from_millis(50)).await; // Brief execution
            cron.stop().await;
        }
        
        let final_count = *counter.lock().await;
        // May execute during the brief windows
        assert!(final_count <= 20, "Rapid cycles should limit executions, got {}", final_count);

        // Clean up
        cron.remove(job_id).await;
    }

    // ASYNC THREAD SAFETY & MEMORY SAFETY TESTS

    #[tokio::test]
    async fn test_async_concurrent_job_access() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;
        
        let shared_counter = Arc::new(AtomicUsize::new(0));
        let access_count = Arc::new(AtomicUsize::new(0));
        
        let mut job_ids = Vec::new();
        for _ in 0..5 {
            let counter = shared_counter.clone();
            let access = access_count.clone();
            let job_id = cron.add_fn("* * * * * * *", move || {
                let counter = counter.clone();
                let access = access.clone();
                async move {
                    access.fetch_add(1, Ordering::SeqCst);
                    let old_value = counter.fetch_add(1, Ordering::SeqCst);
                    // Simulate some async work
                    tokio::time::sleep(Duration::from_millis(10)).await;
                    let new_value = counter.load(Ordering::SeqCst);
                    assert!(new_value > old_value, "Counter should increase");
                }
            }).await.unwrap();
            job_ids.push(job_id);
        }
        
        // Let job execute several times
        sleep(Duration::from_millis(3100)).await;
        cron.stop().await;
        
        let final_counter = shared_counter.load(Ordering::SeqCst);
        let total_accesses = access_count.load(Ordering::SeqCst);
        
        assert!(final_counter == total_accesses, 
               "All accesses should be counted: final={}, accesses={}", final_counter, total_accesses);
        assert!(final_counter >= 5, "Should have multiple concurrent accesses");

        // Clean up
        for job_id in job_ids {
            cron.remove(job_id).await;
        }
    }

    #[tokio::test]
    async fn test_async_shared_mutable_state_safety() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;
        
        // Use a shared vector protected by Mutex
        let shared_data = Arc::new(Mutex::new(Vec::new()));
        
        let mut job_ids = Vec::new();
        for i in 0..3 {
            let data = shared_data.clone();
            let job_id = cron.add_fn("* * * * * * *", move || {
                let data = data.clone();
                let value = i;
                async move {
                    let mut vec = data.lock().await;
                    vec.push(value);
                    // Simulate async work while holding the lock
                    tokio::time::sleep(Duration::from_millis(5)).await;
                }
            }).await.unwrap();
            job_ids.push(job_id);
        }
        
        sleep(Duration::from_millis(3100)).await;
        cron.stop().await;
        
        let final_data = shared_data.lock().await;
        assert!(!final_data.is_empty(), "Shared data should have been modified");
        assert!(final_data.len() >= 3, "Should have entries from multiple jobs");

        // Clean up
        for job_id in job_ids {
            cron.remove(job_id).await;
        }
    }

    #[tokio::test]
    async fn test_async_memory_ordering_consistency() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;
        
        let writes = Arc::new(AtomicUsize::new(0));
        let reads = Arc::new(AtomicUsize::new(0));
        let shared_value = Arc::new(AtomicUsize::new(0));
        
        let mut job_ids = Vec::new();

        // Writer job
        let writes_clone = writes.clone();
        let value_clone = shared_value.clone();
        let job_id1 = cron.add_fn("* * * * * * *", move || {
            let writes = writes_clone.clone();
            let value = value_clone.clone();
            async move {
                let old = value.fetch_add(1, Ordering::SeqCst);
                writes.fetch_add(1, Ordering::SeqCst);
                assert!(old < old + 1, "Write should increment value");
            }
        }).await.unwrap();
        job_ids.push(job_id1);

        // Reader job
        let reads_clone = reads.clone();
        let value_clone2 = shared_value.clone();
        let job_id2 = cron.add_fn("*/2 * * * * * *", move || {
            let reads = reads_clone.clone();
            let value = value_clone2.clone();
            async move {
                let _current = value.load(Ordering::SeqCst);
                reads.fetch_add(1, Ordering::SeqCst);
                // Note: current is AtomicUsize which is always >= 0, so we don't need to check
            }
        }).await.unwrap();
        job_ids.push(job_id2);
        
        sleep(Duration::from_millis(3100)).await;
        cron.stop().await;
        
        let final_writes = writes.load(Ordering::SeqCst);
        let final_reads = reads.load(Ordering::SeqCst);
        let final_value = shared_value.load(Ordering::SeqCst);
        
        assert!(final_writes >= 2, "Should have multiple writes");
        assert!(final_reads >= 1, "Should have some reads");
        assert_eq!(final_value, final_writes, "Final value should equal write count");

        // Clean up
        for job_id in job_ids {
            cron.remove(job_id).await;
        }
    }

    #[tokio::test]
    async fn test_async_scheduler_clone_safety() {
        let mut cron1 = AsyncCron::new(Utc);
        
        // Clone the scheduler
        let mut cron2 = cron1.clone();
        
        let counter1 = Arc::new(AtomicUsize::new(0));
        let counter2 = Arc::new(AtomicUsize::new(0));
        
        let count1 = counter1.clone();
        let job_id1 = cron1.add_fn("* * * * * * *", move || {
            let count = count1.clone();
            async move {
                count.fetch_add(1, Ordering::SeqCst);
            }
        }).await.unwrap();

        let count2 = counter2.clone();
        let job_id2 = cron2.add_fn("*/2 * * * * * *", move || {
            let count = count2.clone();
            async move {
                count.fetch_add(1, Ordering::SeqCst);
            }
        }).await.unwrap();
        
        // Start both schedulers
        cron1.start().await;
        cron2.start().await;
        
        sleep(Duration::from_millis(2100)).await;
        
        // Stop both schedulers
        cron1.stop().await;
        cron2.stop().await;
        
        let count1 = counter1.load(Ordering::SeqCst);
        let count2 = counter2.load(Ordering::SeqCst);
        
        // Both should execute independently
        assert!(count1 >= 1, "Clone 1 should execute");
        assert!(count2 >= 1, "Clone 2 should execute");

        // Clean up
        cron1.remove(job_id1).await;
        cron2.remove(job_id2).await;
    }

    #[tokio::test]
    async fn test_async_cross_thread_job_execution() {
        use std::thread;
        
        let mut cron = AsyncCron::new(Utc);
        
        let main_thread_id = thread::current().id();
        let execution_threads = Arc::new(Mutex::new(Vec::new()));
        let threads_clone = execution_threads.clone();

        let job_id = cron.add_fn("* * * * * * *", move || {
            let threads = threads_clone.clone();
            async move {
                let current_thread = thread::current().id();
                threads.lock().await.push(current_thread);
            }
        }).await.unwrap();
        
        cron.start().await;
        sleep(Duration::from_millis(2100)).await;
        cron.stop().await;
        
        let threads = execution_threads.lock().await;
        assert!(!threads.is_empty(), "Should have captured execution threads");
        
        // In async context, jobs may run on different threads than main
        let _has_different_thread = threads.iter().any(|&tid| tid != main_thread_id);
        // This may or may not be true depending on the async runtime, so we just verify execution occurred
        assert!(threads.len() >= 1, "Should have at least one execution thread record");

        // Clean up
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_async_large_scale_concurrent_execution() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;
        
        let total_executions = Arc::new(AtomicUsize::new(0));
        let job_count = 50;
        let mut job_ids = Vec::new();
        
        // Add many concurrent jobs
        for _ in 0..job_count {
            let counter = total_executions.clone();
            let job_id = cron.add_fn("* * * * * * *", move || {
                let counter = counter.clone();
                async move {
                    counter.fetch_add(1, Ordering::SeqCst);
                    // Simulate minimal async work
                    tokio::time::sleep(Duration::from_millis(1)).await;
                }
            }).await.unwrap();
            job_ids.push(job_id);
        }
        
        sleep(Duration::from_millis(2100)).await;
        cron.stop().await;
        
        let total = total_executions.load(Ordering::SeqCst);
        // Should have significant concurrent execution
        assert!(total >= job_count, "Should execute all jobs at least once, got {} for {} jobs", total, job_count);

        // Clean up
        for job_id in job_ids {
            cron.remove(job_id).await;
        }
    }

    #[tokio::test]
    async fn test_async_job_removal_thread_safety() {
        let mut cron = AsyncCron::new(Utc);
        cron.start().await;
        
        let execution_count = Arc::new(AtomicUsize::new(0));
        let mut job_ids = Vec::new();
        
        // Add multiple jobs
        for _ in 0..10 {
            let count = execution_count.clone();
            let job_id = cron.add_fn("* * * * * * *", move || {
                let count = count.clone();
                async move {
                    count.fetch_add(1, Ordering::SeqCst);
                    // Simulate work
                    tokio::time::sleep(Duration::from_millis(100)).await;
                }
            }).await.unwrap();
            job_ids.push(job_id);
        }
        
        // Let jobs start executing
        sleep(Duration::from_millis(500)).await;
        
        // Remove jobs while they might be executing
        for &job_id in job_ids.iter().take(5) {
            cron.remove(job_id).await;
            sleep(Duration::from_millis(50)).await; // Stagger removals
        }
        
        // Continue execution while removal happens
        sleep(Duration::from_millis(1000)).await;
        cron.stop().await;
        
        let final_count = execution_count.load(Ordering::SeqCst);
        
        // Should complete without deadlock or panic
        assert!(final_count >= 5, "Some jobs should have executed before removal");

        // Clean up remaining jobs
        for &job_id in job_ids.iter().skip(5) {
            cron.remove(job_id).await;
        }
    }

    #[tokio::test]
    async fn test_timezone_differences() {
        use chrono::FixedOffset;
        
        let _utc_cron = AsyncCron::new(Utc);
        let tokyo_tz = FixedOffset::east_opt(9 * 3600).unwrap();
        let _tokyo_cron = AsyncCron::new(tokyo_tz);
        
        // Just verify that different timezones can be created and used
        let mut utc_mut = _utc_cron;
        let _job_id = utc_mut.add_fn("0 0 12 * * * *", || async {
            println!("Noon in the scheduler's timezone");
        }).await.unwrap();
        
        // Test that the scheduler works with the timezone  
        utc_mut.start().await;
        tokio::time::sleep(Duration::from_millis(100)).await;
        utc_mut.stop().await;
    }

    #[tokio::test]
    async fn test_set_timezone() {
        // Create with FixedOffset initially so we can set another FixedOffset later
        let initial_tz = FixedOffset::east_opt(0).unwrap(); // UTC equivalent
        let mut cron = AsyncCron::new(initial_tz);
        
        // Add a job with initial timezone
        let job_id = cron.add_fn("* * * * * * *", || async {
            println!("Test job");
        }).await.unwrap();
        
        // Change timezone to Tokyo (UTC+9)
        let tokyo_tz = FixedOffset::east_opt(9 * 3600).unwrap();
        cron.set_timezone(tokyo_tz);
        
        // Should be able to add jobs after timezone change
        let job_id2 = cron.add_fn("*/2 * * * * * *", || async {
            println!("Job with new timezone");
        }).await.unwrap();
        
        // Clean up
        cron.remove(job_id).await;
        cron.remove(job_id2).await;
    }

    #[tokio::test]
    async fn test_remove_entry_directly() {
        let mut cron = AsyncCron::new(Utc);
        
        // Add a job
        let job_id = cron.add_fn("* * * * * * *", || async {
            println!("Test job");
        }).await.unwrap();
        
        // Remove the job using the remove method (which calls remove_entry internally)
        cron.remove(job_id).await;
        
        // Try to remove the same job again (should not cause issues)
        cron.remove(job_id).await;
        
        // Try to remove a non-existent job ID
        cron.remove(9999).await;
    }

    #[tokio::test]
    async fn test_remove_while_running() {
        let mut cron = AsyncCron::new(Utc);
        let counter = Arc::new(AtomicUsize::new(0));
        let counter_clone = counter.clone();
        
        // Add a job that increments a counter
        let job_id = cron.add_fn("*/50 * * * * * *", move || {
            let counter = counter_clone.clone();
            async move {
                counter.fetch_add(1, Ordering::SeqCst);
            }
        }).await.unwrap();
        
        // Start the cron
        cron.start().await;
        
        // Wait a bit to ensure the scheduler is running
        tokio::time::sleep(Duration::from_millis(10)).await;
        
        // Remove the job while running (this should go through the channel)
        cron.remove(job_id).await;
        
        cron.stop().await;
    }

    #[tokio::test]
    async fn test_schedule_method_indirectly() {
        let mut cron = AsyncCron::new(Utc);
        
        // Test scheduling with different types of jobs
        let counter = Arc::new(AtomicUsize::new(0));
        
        // Simple closure
        let _job1 = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Closure with capture
        let counter_clone = counter.clone();
        let _job2 = cron.add_fn("* * * * * * *", move || {
            let counter = counter_clone.clone();
            async move {
                counter.fetch_add(1, Ordering::SeqCst);
            }
        }).await.unwrap();
        
        // Complex async closure
        let _job3 = cron.add_fn("* * * * * * *", || async {
            tokio::time::sleep(Duration::from_millis(1)).await;
        }).await.unwrap();
    }

    #[tokio::test]
    async fn test_add_job_to_running_scheduler() {
        let mut cron = AsyncCron::new(Utc);
        let counter = Arc::new(AtomicUsize::new(0));
        
        // Start the cron first
        cron.start().await;
        
        // Wait to ensure scheduler is running
        tokio::time::sleep(Duration::from_millis(10)).await;
        
        // Add a job while running (should go through the channel)
        let counter_clone = counter.clone();
        let _job_id = cron.add_fn("*/30 * * * * * *", move || {
            let counter = counter_clone.clone();
            async move {
                counter.fetch_add(1, Ordering::SeqCst);
            }
        }).await.unwrap();
        
        cron.stop().await;
    }

    #[tokio::test]
    async fn test_start_blocking_edge_cases() {
        let mut cron = AsyncCron::new(Utc);
        let executed = Arc::new(AtomicBool::new(false));
        let executed_clone = executed.clone();
        
        // Add a job that should execute soon
        let _job_id = cron.add_fn("* * * * * * *", move || {
            let executed = executed_clone.clone();
            async move {
                executed.store(true, Ordering::SeqCst);
            }
        }).await.unwrap();
        
        // Start blocking in a separate task
        let mut cron_clone = cron.clone();
        let blocking_handle = tokio::spawn(async move {
            cron_clone.start_blocking().await;
        });
        
        // Wait a bit for job to execute
        tokio::time::sleep(Duration::from_millis(1100)).await;
        
        // Stop the scheduler
        cron.stop().await;
        
        // Wait for blocking task to finish
        let _ = tokio::time::timeout(Duration::from_secs(5), blocking_handle).await;
        
        // Verify job executed
        assert!(executed.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn test_multiple_stop_calls() {
        let mut cron = AsyncCron::new(Utc);
        
        cron.start().await;
        
        // Multiple stop calls should not cause issues
        cron.stop().await;
        cron.stop().await;
        cron.stop().await;
    }

    #[tokio::test]
    async fn test_job_execution_order_with_same_schedule() {
        let mut cron = AsyncCron::new(Utc);
        let execution_order = Arc::new(Mutex::new(Vec::new()));
        
        // Add multiple jobs with the same schedule
        for i in 0..3 {
            let execution_order_clone = execution_order.clone();
            let _job_id = cron.add_fn("* * * * * * *", move || {
                let execution_order = execution_order_clone.clone();
                let job_num = i;
                async move {
                    execution_order.lock().await.push(job_num);
                }
            }).await.unwrap();
        }
        
        cron.start().await;
        
        // Wait for jobs to execute
        tokio::time::sleep(Duration::from_millis(1100)).await;
        
        cron.stop().await;
        
        // Check that all jobs executed (each job may execute multiple times)
        let order = execution_order.lock().await;
        assert!(order.len() >= 3, "Should have at least 3 executions, got {}", order.len());
        assert!(order.contains(&0), "Job 0 should have executed");
        assert!(order.contains(&1), "Job 1 should have executed");
        assert!(order.contains(&2), "Job 2 should have executed");
    }

    #[tokio::test]
    async fn test_invalid_cron_expression_async() {
        let mut cron = AsyncCron::new(Utc);
        
        // Test various invalid cron expressions
        let invalid_expressions = vec![
            "invalid",
            "* * * * *",  // too few fields
            "60 * * * * * *",  // invalid second (>59)
            "* 60 * * * * *",  // invalid minute (>59)
            "* * 25 * * * *",  // invalid hour (>23)
            "* * * 32 * * *",  // invalid day (>31)
            "* * * * 13 * *",  // invalid month (>12)
            "* * * * * 8 *",   // invalid weekday (>7)
            "",  // empty string
            "* * * * * * * *",  // too many fields
        ];
        
        for expr in invalid_expressions {
            let result = cron.add_fn(expr, || async {}).await;
            assert!(result.is_err(), "Expected error for expression: {}", expr);
        }
    }

    #[tokio::test]
    async fn test_timezone_scheduling_differences() {
        use chrono::FixedOffset;
        
        let _utc_cron = AsyncCron::new(Utc);
        let tokyo_tz = FixedOffset::east_opt(9 * 3600).unwrap();
        let _tokyo_cron = AsyncCron::new(tokyo_tz);
        
        // Get current time using chrono directly instead of private now() method
        let utc_now = Utc::now();
        let tokyo_now = utc_now.with_timezone(&tokyo_tz);
        
        // The difference should be approximately 9 hours (allowing for small timing differences)
        let time_diff = (tokyo_now.timestamp() - utc_now.timestamp()).abs();
        let expected_diff = 0; // Same instant in time, just different timezone representation
        
        // Times should be the same instant, just in different timezones
        assert_eq!(time_diff, expected_diff, "Same instant should have 0 time difference, got {} seconds", time_diff);
        
        // But the hour should be different due to timezone offset
        assert_ne!(tokyo_now.hour(), utc_now.hour(), "Hours should differ due to timezone");
    }

    #[tokio::test]
    async fn test_concurrent_add_remove_operations() {
        let cron = Arc::new(Mutex::new(AsyncCron::new(Utc)));
        let mut handles = vec![];
        
        // Start multiple tasks that add and remove jobs concurrently
        for _i in 0..10 {
            let cron_clone = cron.clone();
            let handle = tokio::spawn(async move {
                let mut cron = cron_clone.lock().await;
                let job_id = cron.add_fn("* * * * * * *", move || {
                    let _job_num = _i;
                    async move {
                        tokio::time::sleep(Duration::from_millis(1)).await;
                        println!("Job {} executed", _job_num);
                    }
                }).await.unwrap();
                
                // Remove the job immediately
                cron.remove(job_id).await;
            });
            handles.push(handle);
        }
        
        // Wait for all operations to complete
        for handle in handles {
            handle.await.unwrap();
        }
    }

    #[tokio::test]
    async fn test_job_execution_with_long_running_tasks() {
        let mut cron = AsyncCron::new(Utc);
        let execution_count = Arc::new(AtomicUsize::new(0));
        
        // Add a long-running job
        let execution_count_clone = execution_count.clone();
        let _job_id = cron.add_fn("* * * * * * *", move || {
            let count = execution_count_clone.clone();
            async move {
                // Simulate a long-running task
                tokio::time::sleep(Duration::from_millis(500)).await;
                count.fetch_add(1, Ordering::SeqCst);
            }
        }).await.unwrap();
        
        cron.start().await;
        
        // Wait for multiple executions
        tokio::time::sleep(Duration::from_millis(2500)).await;
        
        cron.stop().await;
        
        // Should have executed multiple times despite long duration
        let count = execution_count.load(Ordering::SeqCst);
        assert!(count >= 2, "Expected at least 2 executions, got {}", count);
    }

    #[tokio::test]
    async fn test_different_timezone_scheduling() {
        use chrono::FixedOffset;
        
        let utc_cron = AsyncCron::new(Utc);
        let tokyo_tz = FixedOffset::east_opt(9 * 3600).unwrap();
        let tokyo_cron = AsyncCron::new(tokyo_tz);
        
        // Both should be able to create jobs successfully
        let mut utc_mut = utc_cron;
        let mut tokyo_mut = tokyo_cron;
        
        let utc_job = utc_mut.add_fn("* * * * * * *", || async {
            println!("UTC job");
        }).await.unwrap();
        
        let tokyo_job = tokyo_mut.add_fn("* * * * * * *", || async {
            println!("Tokyo job");  
        }).await.unwrap();
        
        // Start both schedulers
        utc_mut.start().await;
        tokyo_mut.start().await;
        
        // Let them run briefly
        tokio::time::sleep(Duration::from_millis(1100)).await;
        
        // Stop both
        utc_mut.stop().await;
        tokyo_mut.stop().await;
        
        // Clean up
        utc_mut.remove(utc_job).await;
        tokyo_mut.remove(tokyo_job).await;
    }

    #[tokio::test]
    async fn test_timezone_support() {
        use chrono::FixedOffset;
        
        let utc_cron = AsyncCron::new(Utc);
        let tokyo_tz = FixedOffset::east_opt(9 * 3600).unwrap();
        let tokyo_cron = AsyncCron::new(tokyo_tz);
        
        // Both should successfully create jobs
        let mut utc_mut = utc_cron;
        let mut tokyo_mut = tokyo_cron;
        
        let _utc_job = utc_mut.add_fn("* * * * * * *", || async {}).await.unwrap();
        let _tokyo_job = tokyo_mut.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Both should start successfully  
        utc_mut.start().await;
        tokyo_mut.start().await;
        
        // Brief execution
        tokio::time::sleep(Duration::from_millis(100)).await;
        
        // Both should stop successfully
        utc_mut.stop().await;
        tokyo_mut.stop().await;
    }

    // COVERAGE IMPROVEMENT TESTS

    #[tokio::test]
    async fn test_remove_from_stopped_scheduler() {
        let mut cron = AsyncCron::new(Utc);
        
        // Add a job to stopped scheduler
        let job_id = cron.add_fn("* * * * * * *", || async {
            println!("Test job");
        }).await.unwrap();
        
        // Remove from stopped scheduler (should call remove_entry directly)
        cron.remove(job_id).await;
        
        // Verify job was removed by trying to remove again
        cron.remove(job_id).await; // Should not panic
        
        // Remove non-existent job
        cron.remove(9999).await; // Should not panic
    }

    #[tokio::test]
    async fn test_schedule_method_coverage() {
        let mut cron = AsyncCron::new(Utc);
        
        // Test adding job when scheduler is not running (covers fallback branch)
        let job_id1 = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Start scheduler
        cron.start().await;
        
        // Test adding job when scheduler IS running (covers channel send)
        let job_id2 = cron.add_fn("*/2 * * * * * *", || async {}).await.unwrap();
        
        tokio::time::sleep(Duration::from_millis(100)).await;
        cron.stop().await;
        
        // Clean up
        cron.remove(job_id1).await;
        cron.remove(job_id2).await;
    }

    #[tokio::test]
    async fn test_edge_case_cron_schedule() {
        let mut cron = AsyncCron::new(Utc);
        
        // Test schedule that might produce None for next execution
        // Using a schedule that runs only on Feb 30th (which doesn't exist)
        match cron.add_fn("0 0 0 30 2 * *", || async {}).await {
            Ok(job_id) => {
                // If it somehow works, clean up
                cron.remove(job_id).await;
            },
            Err(_) => {
                // Expected - invalid date
            }
        }
        
        // Test with valid but complex schedule
        let job_id = cron.add_fn("0 0 12 * * 1-5 *", || async {
            println!("Weekdays at noon");
        }).await.unwrap();
        
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_scheduler_with_empty_schedule() {
        let mut cron = AsyncCron::new(Utc);
        
        // Start scheduler with no jobs to cover empty entries case
        cron.start().await;
        
        // Let it run briefly
        tokio::time::sleep(Duration::from_millis(100)).await;
        
        // Stop scheduler
        cron.stop().await;
        
        // Add job after stopping
        let job_id = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Remove it
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_stop_channel_edge_cases() {
        let mut cron = AsyncCron::new(Utc);
        
        // Test multiple stop calls
        cron.stop().await;
        cron.stop().await;
        cron.stop().await;
        
        // Start and stop quickly
        cron.start().await;
        cron.stop().await;
        
        // Start again and add job
        cron.start().await;
        let job_id = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Stop and clean up
        cron.stop().await;
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_job_scheduling_edge_cases() {
        let mut cron = AsyncCron::new(Utc);
        
        // Test job that schedules very far in the future
        let far_future_job = cron.add_fn("0 0 0 1 1 * 2030", || async {
            println!("Far future job");
        }).await.unwrap();
        
        // Test job with immediate execution
        let immediate_job = cron.add_fn("* * * * * * *", || async {
            println!("Immediate job");
        }).await.unwrap();
        
        cron.start().await;
        tokio::time::sleep(Duration::from_millis(100)).await;
        cron.stop().await;
        
        // Clean up
        cron.remove(far_future_job).await;
        cron.remove(immediate_job).await;
    }

    #[tokio::test]
    async fn test_remove_when_not_running_coverage() {
        let mut cron = AsyncCron::new(Utc);
        
        // Add job when NOT running
        let job_id = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Remove when NOT running - this should hit line 235 (remove_entry path)
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_schedule_when_running_coverage() {
        let mut cron = AsyncCron::new(Utc);
        
        // Start scheduler first
        cron.start().await;
        
        // Brief wait to ensure scheduler is fully started
        tokio::time::sleep(Duration::from_millis(50)).await;
        
        // Add job when running - this should hit line 331 (channel send path)
        let job_id = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Remove when running - this should hit the channel send in remove
        cron.remove(job_id).await;
        
        cron.stop().await;
    }

    #[tokio::test]
    async fn test_schedule_with_start_blocking_coverage() {
        let mut cron = AsyncCron::new(Utc);
        
        // Use start_blocking in a task to ensure channels are set up
        let mut cron_clone = cron.clone();
        let handle = tokio::spawn(async move {
            cron_clone.start_blocking().await;
        });
        
        // Wait for start_blocking to set up channels
        tokio::time::sleep(Duration::from_millis(100)).await;
        
        // Now add job - this should hit the channel send path (line 331)
        let job_id = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Remove job - this should hit the channel send in remove
        cron.remove(job_id).await;
        
        // Stop the scheduler
        cron.stop().await;
        
        // Wait for the task to finish
        let _ = tokio::time::timeout(Duration::from_secs(1), handle).await;
    }

    #[tokio::test]
    async fn test_schedule_when_not_running_coverage() {
        let mut cron = AsyncCron::new(Utc);
        
        // Add job when NOT running - this should hit line 356 (fallback path)
        let job_id = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Clean up
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_async_entry_get_next_edge_case() {
        let mut cron = AsyncCron::new(Utc);
        
        // Test with a schedule that might return None in some edge cases
        // This should test line 153 in async_entry.rs
        let job_id = cron.add_fn("0 0 0 31 2 * *", || async {}).await.unwrap(); // Feb 31st (invalid)
        
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_stop_without_channels() {
        let cron = AsyncCron::new(Utc);
        
        // Stop without ever starting - this should test the None case in stop
        cron.stop().await;
    }

    #[tokio::test]
    async fn test_precise_remove_not_running_coverage() {
        let mut cron = AsyncCron::new(Utc);
        
        // Add job when NOT running (scheduler not started yet)
        let job_id = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Remove when NOT running - this should hit the remove_entry path
        // Since we never called start(), the scheduler is not running
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_precise_schedule_running_coverage() {
        let mut cron = AsyncCron::new(Utc);
        
        // Start the scheduler using start_blocking to ensure channels are set up
        let mut cron_clone = cron.clone();
        let handle = tokio::spawn(async move {
            cron_clone.start_blocking().await;
        });
        
        // Wait for start_blocking to fully initialize channels
        tokio::time::sleep(Duration::from_millis(200)).await;
        
        // Now add job when running=true AND channels are set up
        // This should hit the channel send path
        let job_id = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        // Stop and clean up
        cron.stop().await;
        
        // Wait for the blocking task to finish
        let _ = tokio::time::timeout(Duration::from_secs(1), handle).await;
        
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_schedule_fallback_path_coverage() {
        let mut cron = AsyncCron::new(Utc);
        
        // Add job when not running - this should hit the fallback path
        // Since start() hasn't been called, channels aren't set up yet
        let job_id = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        
        cron.remove(job_id).await;
    }

    #[tokio::test]
    async fn test_force_uncovered_paths() {
        let mut cron = AsyncCron::new(Utc);

        // Test case 1: Add and remove job without starting scheduler
        let job_id1 = cron.add_fn("* * * * * * *", || async {}).await.unwrap();
        cron.remove(job_id1).await;

        // Test case 2: Test with potential edge case schedule
        if let Ok(job_id2) = cron.add_fn("0 0 30 2 * * *", || async {}).await {
            cron.remove(job_id2).await;
        }

        // Test case 3: Start scheduler, add job, then stop
        cron.start().await;
        tokio::time::sleep(Duration::from_millis(50)).await;

        let job_id3 = cron.add_fn("* * * * * * *", || async {}).await.unwrap();

        cron.stop().await;
        cron.remove(job_id3).await;
    }

}