SQL Server heap tables fragmentation monitoring
I would suggest that, rather than 'roll-your-own', you save yourself a whole bunch of time and effort and implement Ola Hallengren's Index Maintenance script.

https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html

And, check out Brent Ozar's tweaks for Ola's script

https://www.brentozar.com/archive/2014/12/tweaking-defaults-ola-hallengrens-maintenance-scripts/